blob: 9221b89b1a4a986f2e665191d9bacc56bacb2ab1 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith7a614d82011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Sean Hunt001cad92011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith7a614d82011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssoned961f92009-08-25 02:29:20 +0000210bool
John McCall9ae2f072010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssoned961f92009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000233 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000235
John McCallb4eb64d2010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson9351c172009-08-25 03:18:48 +0000254 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000255}
256
Chris Lattner8123a952008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260void
John McCalld226f652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000264 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
John McCalld226f652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6f526752010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlsson66e30672009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall9ae2f072010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000291}
292
Douglas Gregor61366e92008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000308}
309
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Anders Carlsson5e300d12009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000321}
322
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000388
Francois Pichet8d051e02011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000395 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000409
Francois Pichet8cf90492011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000423 for (FunctionDecl *Older = Old->getPreviousDecl();
424 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCall3d6c1782010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000501 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000502 }
503 }
504
Richard Smith9f569cc2011-10-01 02:31:28 +0000505 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
506 // template has a constexpr specifier then all its declarations shall
507 // contain the constexpr specifier. [Note: An explicit specialization can
508 // differ from the template declaration with respect to the constexpr
509 // specifier. -- end note]
510 //
511 // FIXME: Don't reject changes in constexpr in explicit specializations.
512 if (New->isConstexpr() != Old->isConstexpr()) {
513 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
514 << New << New->isConstexpr();
515 Diag(Old->getLocation(), diag::note_previous_declaration);
516 Invalid = true;
517 }
518
Douglas Gregore13ad832010-02-12 07:32:17 +0000519 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000520 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000521
Douglas Gregorcda9c672009-02-16 17:45:42 +0000522 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000523}
524
Sebastian Redl60618fa2011-03-12 11:50:43 +0000525/// \brief Merge the exception specifications of two variable declarations.
526///
527/// This is called when there's a redeclaration of a VarDecl. The function
528/// checks if the redeclaration might have an exception specification and
529/// validates compatibility and merges the specs if necessary.
530void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
531 // Shortcut if exceptions are disabled.
532 if (!getLangOptions().CXXExceptions)
533 return;
534
535 assert(Context.hasSameType(New->getType(), Old->getType()) &&
536 "Should only be called if types are otherwise the same.");
537
538 QualType NewType = New->getType();
539 QualType OldType = Old->getType();
540
541 // We're only interested in pointers and references to functions, as well
542 // as pointers to member functions.
543 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
544 NewType = R->getPointeeType();
545 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
546 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
547 NewType = P->getPointeeType();
548 OldType = OldType->getAs<PointerType>()->getPointeeType();
549 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
550 NewType = M->getPointeeType();
551 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
552 }
553
554 if (!NewType->isFunctionProtoType())
555 return;
556
557 // There's lots of special cases for functions. For function pointers, system
558 // libraries are hopefully not as broken so that we don't need these
559 // workarounds.
560 if (CheckEquivalentExceptionSpec(
561 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
562 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
563 New->setInvalidDecl();
564 }
565}
566
Chris Lattner3d1cee32008-04-08 05:04:30 +0000567/// CheckCXXDefaultArguments - Verify that the default arguments for a
568/// function declaration are well-formed according to C++
569/// [dcl.fct.default].
570void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
571 unsigned NumParams = FD->getNumParams();
572 unsigned p;
573
574 // Find first parameter with a default argument
575 for (p = 0; p < NumParams; ++p) {
576 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000577 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000578 break;
579 }
580
581 // C++ [dcl.fct.default]p4:
582 // In a given function declaration, all parameters
583 // subsequent to a parameter with a default argument shall
584 // have default arguments supplied in this or previous
585 // declarations. A default argument shall not be redefined
586 // by a later declaration (not even to the same value).
587 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000588 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000589 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000590 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000591 if (Param->isInvalidDecl())
592 /* We already complained about this parameter. */;
593 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000594 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000595 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000596 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000597 else
Mike Stump1eb44332009-09-09 15:08:12 +0000598 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner3d1cee32008-04-08 05:04:30 +0000601 LastMissingDefaultArg = p;
602 }
603 }
604
605 if (LastMissingDefaultArg > 0) {
606 // Some default arguments were missing. Clear out all of the
607 // default arguments up to (and including) the last missing
608 // default argument, so that we leave the function parameters
609 // in a semantically valid state.
610 for (p = 0; p <= LastMissingDefaultArg; ++p) {
611 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000612 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000613 Param->setDefaultArg(0);
614 }
615 }
616 }
617}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000618
Richard Smith9f569cc2011-10-01 02:31:28 +0000619// CheckConstexprParameterTypes - Check whether a function's parameter types
620// are all literal types. If so, return true. If not, produce a suitable
621// diagnostic depending on @p CCK and return false.
622static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
623 Sema::CheckConstexprKind CCK) {
624 unsigned ArgIndex = 0;
625 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
626 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
627 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
628 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
629 SourceLocation ParamLoc = PD->getLocation();
630 if (!(*i)->isDependentType() &&
631 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
632 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
633 << ArgIndex+1 << PD->getSourceRange()
634 << isa<CXXConstructorDecl>(FD) :
635 SemaRef.PDiag(),
636 /*AllowIncompleteType*/ true)) {
637 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
638 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
639 << ArgIndex+1 << PD->getSourceRange()
640 << isa<CXXConstructorDecl>(FD) << *i;
641 return false;
642 }
643 }
644 return true;
645}
646
647// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
648// the requirements of a constexpr function declaration or a constexpr
649// constructor declaration. Return true if it does, false if not.
650//
Richard Smith35340502012-01-13 04:54:00 +0000651// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smith9f569cc2011-10-01 02:31:28 +0000652//
653// \param CCK Specifies whether to produce diagnostics if the function does not
654// satisfy the requirements.
655bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
656 CheckConstexprKind CCK) {
657 assert((CCK != CCK_NoteNonConstexprInstantiation ||
658 (NewFD->getTemplateInstantiationPattern() &&
659 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
660 "only constexpr templates can be instantiated non-constexpr");
661
Richard Smith35340502012-01-13 04:54:00 +0000662 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
663 if (MD && MD->isInstance()) {
664 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smith9f569cc2011-10-01 02:31:28 +0000665 // In addition, either its function-body shall be = delete or = default or
666 // it shall satisfy the following constraints:
667 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000668 //
669 // We apply this to constexpr member functions too: the class cannot be a
670 // literal type, so the members are not permitted to be constexpr.
671 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000672 if (RD->getNumVBases()) {
673 // Note, this is still illegal if the body is = default, since the
674 // implicit body does not satisfy the requirements of a constexpr
675 // constructor. We also reject cases where the body is = delete, as
676 // required by N3308.
677 if (CCK != CCK_Instantiation) {
678 Diag(NewFD->getLocation(),
679 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
680 : diag::note_constexpr_tmpl_virtual_base)
Richard Smith35340502012-01-13 04:54:00 +0000681 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
682 << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +0000683 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
684 E = RD->vbases_end(); I != E; ++I)
685 Diag(I->getSourceRange().getBegin(),
686 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
687 }
688 return false;
689 }
Richard Smith35340502012-01-13 04:54:00 +0000690 }
691
692 if (!isa<CXXConstructorDecl>(NewFD)) {
693 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000694 // The definition of a constexpr function shall satisfy the following
695 // constraints:
696 // - it shall not be virtual;
697 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
698 if (Method && Method->isVirtual()) {
699 if (CCK != CCK_Instantiation) {
700 Diag(NewFD->getLocation(),
701 CCK == CCK_Declaration ? diag::err_constexpr_virtual
702 : diag::note_constexpr_tmpl_virtual);
703
704 // If it's not obvious why this function is virtual, find an overridden
705 // function which uses the 'virtual' keyword.
706 const CXXMethodDecl *WrittenVirtual = Method;
707 while (!WrittenVirtual->isVirtualAsWritten())
708 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
709 if (WrittenVirtual != Method)
Richard Smith35340502012-01-13 04:54:00 +0000710 Diag(WrittenVirtual->getLocation(),
Richard Smith9f569cc2011-10-01 02:31:28 +0000711 diag::note_overridden_virtual_function);
712 }
713 return false;
714 }
715
716 // - its return type shall be a literal type;
717 QualType RT = NewFD->getResultType();
718 if (!RT->isDependentType() &&
719 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
720 PDiag(diag::err_constexpr_non_literal_return) :
721 PDiag(),
722 /*AllowIncompleteType*/ true)) {
723 if (CCK == CCK_NoteNonConstexprInstantiation)
724 Diag(NewFD->getLocation(),
725 diag::note_constexpr_tmpl_non_literal_return) << RT;
726 return false;
727 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 }
729
Richard Smith35340502012-01-13 04:54:00 +0000730 // - each of its parameter types shall be a literal type;
731 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
732 return false;
733
Richard Smith9f569cc2011-10-01 02:31:28 +0000734 return true;
735}
736
737/// Check the given declaration statement is legal within a constexpr function
738/// body. C++0x [dcl.constexpr]p3,p4.
739///
740/// \return true if the body is OK, false if we have diagnosed a problem.
741static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
742 DeclStmt *DS) {
743 // C++0x [dcl.constexpr]p3 and p4:
744 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
745 // contain only
746 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
747 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
748 switch ((*DclIt)->getKind()) {
749 case Decl::StaticAssert:
750 case Decl::Using:
751 case Decl::UsingShadow:
752 case Decl::UsingDirective:
753 case Decl::UnresolvedUsingTypename:
754 // - static_assert-declarations
755 // - using-declarations,
756 // - using-directives,
757 continue;
758
759 case Decl::Typedef:
760 case Decl::TypeAlias: {
761 // - typedef declarations and alias-declarations that do not define
762 // classes or enumerations,
763 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
764 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
765 // Don't allow variably-modified types in constexpr functions.
766 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
767 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
768 << TL.getSourceRange() << TL.getType()
769 << isa<CXXConstructorDecl>(Dcl);
770 return false;
771 }
772 continue;
773 }
774
775 case Decl::Enum:
776 case Decl::CXXRecord:
777 // As an extension, we allow the declaration (but not the definition) of
778 // classes and enumerations in all declarations, not just in typedef and
779 // alias declarations.
780 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
781 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
782 << isa<CXXConstructorDecl>(Dcl);
783 return false;
784 }
785 continue;
786
787 case Decl::Var:
788 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
789 << isa<CXXConstructorDecl>(Dcl);
790 return false;
791
792 default:
793 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
794 << isa<CXXConstructorDecl>(Dcl);
795 return false;
796 }
797 }
798
799 return true;
800}
801
802/// Check that the given field is initialized within a constexpr constructor.
803///
804/// \param Dcl The constexpr constructor being checked.
805/// \param Field The field being checked. This may be a member of an anonymous
806/// struct or union nested within the class being checked.
807/// \param Inits All declarations, including anonymous struct/union members and
808/// indirect members, for which any initialization was provided.
809/// \param Diagnosed Set to true if an error is produced.
810static void CheckConstexprCtorInitializer(Sema &SemaRef,
811 const FunctionDecl *Dcl,
812 FieldDecl *Field,
813 llvm::SmallSet<Decl*, 16> &Inits,
814 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000815 if (Field->isUnnamedBitfield())
816 return;
817
Richard Smith9f569cc2011-10-01 02:31:28 +0000818 if (!Inits.count(Field)) {
819 if (!Diagnosed) {
820 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
821 Diagnosed = true;
822 }
823 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
824 } else if (Field->isAnonymousStructOrUnion()) {
825 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
826 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
827 I != E; ++I)
828 // If an anonymous union contains an anonymous struct of which any member
829 // is initialized, all members must be initialized.
830 if (!RD->isUnion() || Inits.count(*I))
831 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
832 }
833}
834
835/// Check the body for the given constexpr function declaration only contains
836/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
837///
838/// \return true if the body is OK, false if we have diagnosed a problem.
839bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
840 if (isa<CXXTryStmt>(Body)) {
841 // C++0x [dcl.constexpr]p3:
842 // The definition of a constexpr function shall satisfy the following
843 // constraints: [...]
844 // - its function-body shall be = delete, = default, or a
845 // compound-statement
846 //
847 // C++0x [dcl.constexpr]p4:
848 // In the definition of a constexpr constructor, [...]
849 // - its function-body shall not be a function-try-block;
850 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
851 << isa<CXXConstructorDecl>(Dcl);
852 return false;
853 }
854
855 // - its function-body shall be [...] a compound-statement that contains only
856 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
857
858 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
859 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
860 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
861 switch ((*BodyIt)->getStmtClass()) {
862 case Stmt::NullStmtClass:
863 // - null statements,
864 continue;
865
866 case Stmt::DeclStmtClass:
867 // - static_assert-declarations
868 // - using-declarations,
869 // - using-directives,
870 // - typedef declarations and alias-declarations that do not define
871 // classes or enumerations,
872 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
873 return false;
874 continue;
875
876 case Stmt::ReturnStmtClass:
877 // - and exactly one return statement;
878 if (isa<CXXConstructorDecl>(Dcl))
879 break;
880
881 ReturnStmts.push_back((*BodyIt)->getLocStart());
882 // FIXME
883 // - every constructor call and implicit conversion used in initializing
884 // the return value shall be one of those allowed in a constant
885 // expression.
886 // Deal with this as part of a general check that the function can produce
887 // a constant expression (for [dcl.constexpr]p5).
888 continue;
889
890 default:
891 break;
892 }
893
894 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
895 << isa<CXXConstructorDecl>(Dcl);
896 return false;
897 }
898
899 if (const CXXConstructorDecl *Constructor
900 = dyn_cast<CXXConstructorDecl>(Dcl)) {
901 const CXXRecordDecl *RD = Constructor->getParent();
902 // - every non-static data member and base class sub-object shall be
903 // initialized;
904 if (RD->isUnion()) {
905 // DR1359: Exactly one member of a union shall be initialized.
906 if (Constructor->getNumCtorInitializers() == 0) {
907 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
908 return false;
909 }
Richard Smith6e433752011-10-10 16:38:04 +0000910 } else if (!Constructor->isDependentContext() &&
911 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000912 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
913
914 // Skip detailed checking if we have enough initializers, and we would
915 // allow at most one initializer per member.
916 bool AnyAnonStructUnionMembers = false;
917 unsigned Fields = 0;
918 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
919 E = RD->field_end(); I != E; ++I, ++Fields) {
920 if ((*I)->isAnonymousStructOrUnion()) {
921 AnyAnonStructUnionMembers = true;
922 break;
923 }
924 }
925 if (AnyAnonStructUnionMembers ||
926 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
927 // Check initialization of non-static data members. Base classes are
928 // always initialized so do not need to be checked. Dependent bases
929 // might not have initializers in the member initializer list.
930 llvm::SmallSet<Decl*, 16> Inits;
931 for (CXXConstructorDecl::init_const_iterator
932 I = Constructor->init_begin(), E = Constructor->init_end();
933 I != E; ++I) {
934 if (FieldDecl *FD = (*I)->getMember())
935 Inits.insert(FD);
936 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
937 Inits.insert(ID->chain_begin(), ID->chain_end());
938 }
939
940 bool Diagnosed = false;
941 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
942 E = RD->field_end(); I != E; ++I)
943 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
944 if (Diagnosed)
945 return false;
946 }
947 }
948
949 // FIXME
950 // - every constructor involved in initializing non-static data members
951 // and base class sub-objects shall be a constexpr constructor;
952 // - every assignment-expression that is an initializer-clause appearing
953 // directly or indirectly within a brace-or-equal-initializer for
954 // a non-static data member that is not named by a mem-initializer-id
955 // shall be a constant expression; and
956 // - every implicit conversion used in converting a constructor argument
957 // to the corresponding parameter type and converting
958 // a full-expression to the corresponding member type shall be one of
959 // those allowed in a constant expression.
960 // Deal with these as part of a general check that the function can produce
961 // a constant expression (for [dcl.constexpr]p5).
962 } else {
963 if (ReturnStmts.empty()) {
964 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
965 return false;
966 }
967 if (ReturnStmts.size() > 1) {
968 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
969 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
970 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
971 return false;
972 }
973 }
974
Richard Smith745f5142012-01-27 01:14:48 +0000975 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
976 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
977 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
978 << isa<CXXConstructorDecl>(Dcl);
979 for (size_t I = 0, N = Diags.size(); I != N; ++I)
980 Diag(Diags[I].first, Diags[I].second);
981 return false;
982 }
983
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 return true;
985}
986
Douglas Gregorb48fe382008-10-31 09:07:45 +0000987/// isCurrentClassName - Determine whether the identifier II is the
988/// name of the class type currently being defined. In the case of
989/// nested classes, this will only return true if II is the name of
990/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
992 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000993 assert(getLangOptions().CPlusPlus && "No class names in C!");
994
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000995 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000996 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000997 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000998 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
999 } else
1000 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1001
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001002 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001003 return &II == CurDecl->getIdentifier();
1004 else
1005 return false;
1006}
1007
Mike Stump1eb44332009-09-09 15:08:12 +00001008/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001009///
1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1011/// and returns NULL otherwise.
1012CXXBaseSpecifier *
1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1014 SourceRange SpecifierRange,
1015 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001016 TypeSourceInfo *TInfo,
1017 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001018 QualType BaseType = TInfo->getType();
1019
Douglas Gregor2943aed2009-03-03 04:44:36 +00001020 // C++ [class.union]p1:
1021 // A union shall not have base classes.
1022 if (Class->isUnion()) {
1023 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1024 << SpecifierRange;
1025 return 0;
1026 }
1027
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001028 if (EllipsisLoc.isValid() &&
1029 !TInfo->getType()->containsUnexpandedParameterPack()) {
1030 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1031 << TInfo->getTypeLoc().getSourceRange();
1032 EllipsisLoc = SourceLocation();
1033 }
1034
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001036 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001037 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001038 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001039
1040 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001041
1042 // Base specifiers must be record types.
1043 if (!BaseType->isRecordType()) {
1044 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1045 return 0;
1046 }
1047
1048 // C++ [class.union]p1:
1049 // A union shall not be used as a base class.
1050 if (BaseType->isUnionType()) {
1051 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1052 return 0;
1053 }
1054
1055 // C++ [class.derived]p2:
1056 // The class-name in a base-specifier shall not be an incompletely
1057 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001058 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001059 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001060 << SpecifierRange)) {
1061 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001062 return 0;
John McCall572fc622010-08-17 07:23:57 +00001063 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001064
Eli Friedman1d954f62009-08-15 21:55:26 +00001065 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001066 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001067 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001068 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001069 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001070 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1071 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001072
Anders Carlsson1d209272011-03-25 14:55:14 +00001073 // C++ [class]p3:
1074 // If a class is marked final and it appears as a base-type-specifier in
1075 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001076 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001077 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1078 << CXXBaseDecl->getDeclName();
1079 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1080 << CXXBaseDecl->getDeclName();
1081 return 0;
1082 }
1083
John McCall572fc622010-08-17 07:23:57 +00001084 if (BaseDecl->isInvalidDecl())
1085 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001086
1087 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001088 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001089 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001090 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001091}
1092
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001093/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1094/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001095/// example:
1096/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001097/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001098BaseResult
John McCalld226f652010-08-21 09:40:31 +00001099Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001100 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001101 ParsedType basetype, SourceLocation BaseLoc,
1102 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001103 if (!classdecl)
1104 return true;
1105
Douglas Gregor40808ce2009-03-09 23:48:35 +00001106 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001107 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001108 if (!Class)
1109 return true;
1110
Nick Lewycky56062202010-07-26 16:56:01 +00001111 TypeSourceInfo *TInfo = 0;
1112 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001113
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001114 if (EllipsisLoc.isInvalid() &&
1115 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001116 UPPC_BaseType))
1117 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001118
Douglas Gregor2943aed2009-03-03 04:44:36 +00001119 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001120 Virtual, Access, TInfo,
1121 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001122 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Douglas Gregor2943aed2009-03-03 04:44:36 +00001124 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001125}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001126
Douglas Gregor2943aed2009-03-03 04:44:36 +00001127/// \brief Performs the actual work of attaching the given base class
1128/// specifiers to a C++ class.
1129bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1130 unsigned NumBases) {
1131 if (NumBases == 0)
1132 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001133
1134 // Used to keep track of which base types we have already seen, so
1135 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001136 // that the key is always the unqualified canonical type of the base
1137 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001138 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1139
1140 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001141 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001143 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001144 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001145 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001146 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001147 if (KnownBaseTypes[NewBaseType]) {
1148 // C++ [class.mi]p3:
1149 // A class shall not be specified as a direct base class of a
1150 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001151 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001152 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001153 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001155
1156 // Delete the duplicate base class specifier; we're going to
1157 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001158 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159
1160 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001161 } else {
1162 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001163 KnownBaseTypes[NewBaseType] = Bases[idx];
1164 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001165 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001166 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1167 if (RD->hasAttr<WeakAttr>())
1168 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001169 }
1170 }
1171
1172 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001173 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001174
1175 // Delete the remaining (good) base class specifiers, since their
1176 // data has been copied into the CXXRecordDecl.
1177 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001178 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001179
1180 return Invalid;
1181}
1182
1183/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1184/// class, after checking whether there are any duplicate base
1185/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001186void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001187 unsigned NumBases) {
1188 if (!ClassDecl || !Bases || !NumBases)
1189 return;
1190
1191 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001192 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001193 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001194}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001195
John McCall3cb0ebd2010-03-10 03:28:59 +00001196static CXXRecordDecl *GetClassForType(QualType T) {
1197 if (const RecordType *RT = T->getAs<RecordType>())
1198 return cast<CXXRecordDecl>(RT->getDecl());
1199 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1200 return ICT->getDecl();
1201 else
1202 return 0;
1203}
1204
Douglas Gregora8f32e02009-10-06 17:59:45 +00001205/// \brief Determine whether the type \p Derived is a C++ class that is
1206/// derived from the type \p Base.
1207bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1208 if (!getLangOptions().CPlusPlus)
1209 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001210
1211 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1212 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001213 return false;
1214
John McCall3cb0ebd2010-03-10 03:28:59 +00001215 CXXRecordDecl *BaseRD = GetClassForType(Base);
1216 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217 return false;
1218
John McCall86ff3082010-02-04 22:26:26 +00001219 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1220 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001221}
1222
1223/// \brief Determine whether the type \p Derived is a C++ class that is
1224/// derived from the type \p Base.
1225bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1226 if (!getLangOptions().CPlusPlus)
1227 return false;
1228
John McCall3cb0ebd2010-03-10 03:28:59 +00001229 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1230 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001231 return false;
1232
John McCall3cb0ebd2010-03-10 03:28:59 +00001233 CXXRecordDecl *BaseRD = GetClassForType(Base);
1234 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001235 return false;
1236
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1238}
1239
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001240void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001241 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001242 assert(BasePathArray.empty() && "Base path array must be empty!");
1243 assert(Paths.isRecordingPaths() && "Must record paths!");
1244
1245 const CXXBasePath &Path = Paths.front();
1246
1247 // We first go backward and check if we have a virtual base.
1248 // FIXME: It would be better if CXXBasePath had the base specifier for
1249 // the nearest virtual base.
1250 unsigned Start = 0;
1251 for (unsigned I = Path.size(); I != 0; --I) {
1252 if (Path[I - 1].Base->isVirtual()) {
1253 Start = I - 1;
1254 break;
1255 }
1256 }
1257
1258 // Now add all bases.
1259 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001260 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001261}
1262
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001263/// \brief Determine whether the given base path includes a virtual
1264/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001265bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1266 for (CXXCastPath::const_iterator B = BasePath.begin(),
1267 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001268 B != BEnd; ++B)
1269 if ((*B)->isVirtual())
1270 return true;
1271
1272 return false;
1273}
1274
Douglas Gregora8f32e02009-10-06 17:59:45 +00001275/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1276/// conversion (where Derived and Base are class types) is
1277/// well-formed, meaning that the conversion is unambiguous (and
1278/// that all of the base classes are accessible). Returns true
1279/// and emits a diagnostic if the code is ill-formed, returns false
1280/// otherwise. Loc is the location where this routine should point to
1281/// if there is an error, and Range is the source range to highlight
1282/// if there is an error.
1283bool
1284Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001285 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001286 unsigned AmbigiousBaseConvID,
1287 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001288 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001289 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001290 // First, determine whether the path from Derived to Base is
1291 // ambiguous. This is slightly more expensive than checking whether
1292 // the Derived to Base conversion exists, because here we need to
1293 // explore multiple paths to determine if there is an ambiguity.
1294 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1295 /*DetectVirtual=*/false);
1296 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1297 assert(DerivationOkay &&
1298 "Can only be used with a derived-to-base conversion");
1299 (void)DerivationOkay;
1300
1301 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001302 if (InaccessibleBaseID) {
1303 // Check that the base class can be accessed.
1304 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1305 InaccessibleBaseID)) {
1306 case AR_inaccessible:
1307 return true;
1308 case AR_accessible:
1309 case AR_dependent:
1310 case AR_delayed:
1311 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001312 }
John McCall6b2accb2010-02-10 09:31:12 +00001313 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001314
1315 // Build a base path if necessary.
1316 if (BasePath)
1317 BuildBasePathArray(Paths, *BasePath);
1318 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001319 }
1320
1321 // We know that the derived-to-base conversion is ambiguous, and
1322 // we're going to produce a diagnostic. Perform the derived-to-base
1323 // search just one more time to compute all of the possible paths so
1324 // that we can print them out. This is more expensive than any of
1325 // the previous derived-to-base checks we've done, but at this point
1326 // performance isn't as much of an issue.
1327 Paths.clear();
1328 Paths.setRecordingPaths(true);
1329 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1330 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1331 (void)StillOkay;
1332
1333 // Build up a textual representation of the ambiguous paths, e.g.,
1334 // D -> B -> A, that will be used to illustrate the ambiguous
1335 // conversions in the diagnostic. We only print one of the paths
1336 // to each base class subobject.
1337 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1338
1339 Diag(Loc, AmbigiousBaseConvID)
1340 << Derived << Base << PathDisplayStr << Range << Name;
1341 return true;
1342}
1343
1344bool
1345Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001346 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001347 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001348 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001350 IgnoreAccess ? 0
1351 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001352 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001353 Loc, Range, DeclarationName(),
1354 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355}
1356
1357
1358/// @brief Builds a string representing ambiguous paths from a
1359/// specific derived class to different subobjects of the same base
1360/// class.
1361///
1362/// This function builds a string that can be used in error messages
1363/// to show the different paths that one can take through the
1364/// inheritance hierarchy to go from the derived class to different
1365/// subobjects of a base class. The result looks something like this:
1366/// @code
1367/// struct D -> struct B -> struct A
1368/// struct D -> struct C -> struct A
1369/// @endcode
1370std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1371 std::string PathDisplayStr;
1372 std::set<unsigned> DisplayedPaths;
1373 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1374 Path != Paths.end(); ++Path) {
1375 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1376 // We haven't displayed a path to this particular base
1377 // class subobject yet.
1378 PathDisplayStr += "\n ";
1379 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1380 for (CXXBasePath::const_iterator Element = Path->begin();
1381 Element != Path->end(); ++Element)
1382 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1383 }
1384 }
1385
1386 return PathDisplayStr;
1387}
1388
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001389//===----------------------------------------------------------------------===//
1390// C++ class member Handling
1391//===----------------------------------------------------------------------===//
1392
Abramo Bagnara6206d532010-06-05 05:09:32 +00001393/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001394bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1395 SourceLocation ASLoc,
1396 SourceLocation ColonLoc,
1397 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001398 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001399 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001400 ASLoc, ColonLoc);
1401 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001402 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001403}
1404
Anders Carlsson9e682d92011-01-20 05:57:14 +00001405/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001406void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001407 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001408 if (!MD || !MD->isVirtual())
1409 return;
1410
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001411 if (MD->isDependentContext())
1412 return;
1413
Anders Carlsson9e682d92011-01-20 05:57:14 +00001414 // C++0x [class.virtual]p3:
1415 // If a virtual function is marked with the virt-specifier override and does
1416 // not override a member function of a base class,
1417 // the program is ill-formed.
1418 bool HasOverriddenMethods =
1419 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001420 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001421 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001422 diag::err_function_marked_override_not_overriding)
1423 << MD->getDeclName();
1424 return;
1425 }
1426}
1427
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001428/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1429/// function overrides a virtual member function marked 'final', according to
1430/// C++0x [class.virtual]p3.
1431bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1432 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001433 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001434 return false;
1435
1436 Diag(New->getLocation(), diag::err_final_function_overridden)
1437 << New->getDeclName();
1438 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1439 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001440}
1441
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001442/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1443/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001444/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1445/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1446/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001447Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001448Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001449 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001450 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001451 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001452 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001453 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1454 DeclarationName Name = NameInfo.getName();
1455 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001456
1457 // For anonymous bitfields, the location should point to the type.
1458 if (Loc.isInvalid())
1459 Loc = D.getSourceRange().getBegin();
1460
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001461 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001462
John McCall4bde1e12010-06-04 08:34:12 +00001463 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001464 assert(!DS.isFriendSpecified());
1465
Richard Smith1ab0d902011-06-25 02:28:38 +00001466 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001467
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001468 // C++ 9.2p6: A member shall not be declared to have automatic storage
1469 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001470 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1471 // data members and cannot be applied to names declared const or static,
1472 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473 switch (DS.getStorageClassSpec()) {
1474 case DeclSpec::SCS_unspecified:
1475 case DeclSpec::SCS_typedef:
1476 case DeclSpec::SCS_static:
1477 // FALL THROUGH.
1478 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001479 case DeclSpec::SCS_mutable:
1480 if (isFunc) {
1481 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001482 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001483 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001484 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Sebastian Redla11f42f2008-11-17 23:24:37 +00001486 // FIXME: It would be nicer if the keyword was ignored only for this
1487 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001488 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001489 }
1490 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001491 default:
1492 if (DS.getStorageClassSpecLoc().isValid())
1493 Diag(DS.getStorageClassSpecLoc(),
1494 diag::err_storageclass_invalid_for_member);
1495 else
1496 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1497 D.getMutableDeclSpec().ClearStorageClassSpecs();
1498 }
1499
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1501 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001502 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503
1504 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001505 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001506 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001507
1508 // Data members must have identifiers for names.
1509 if (Name.getNameKind() != DeclarationName::Identifier) {
1510 Diag(Loc, diag::err_bad_variable_name)
1511 << Name;
1512 return 0;
1513 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001514
Douglas Gregorf2503652011-09-21 14:40:46 +00001515 IdentifierInfo *II = Name.getAsIdentifierInfo();
1516
1517 // Member field could not be with "template" keyword.
1518 // So TemplateParameterLists should be empty in this case.
1519 if (TemplateParameterLists.size()) {
1520 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1521 if (TemplateParams->size()) {
1522 // There is no such thing as a member field template.
1523 Diag(D.getIdentifierLoc(), diag::err_template_member)
1524 << II
1525 << SourceRange(TemplateParams->getTemplateLoc(),
1526 TemplateParams->getRAngleLoc());
1527 } else {
1528 // There is an extraneous 'template<>' for this member.
1529 Diag(TemplateParams->getTemplateLoc(),
1530 diag::err_template_member_noparams)
1531 << II
1532 << SourceRange(TemplateParams->getTemplateLoc(),
1533 TemplateParams->getRAngleLoc());
1534 }
1535 return 0;
1536 }
1537
Douglas Gregor922fff22010-10-13 22:19:53 +00001538 if (SS.isSet() && !SS.isInvalid()) {
1539 // The user provided a superfluous scope specifier inside a class
1540 // definition:
1541 //
1542 // class X {
1543 // int X::member;
1544 // };
1545 DeclContext *DC = 0;
1546 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1547 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001548 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001549 else
1550 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1551 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001552
Douglas Gregor922fff22010-10-13 22:19:53 +00001553 SS.clear();
1554 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001555
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001556 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001557 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001558 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001559 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001560 assert(!HasDeferredInit);
1561
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001562 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001563 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001564 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001565 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001566
1567 // Non-instance-fields can't have a bitfield.
1568 if (BitWidth) {
1569 if (Member->isInvalidDecl()) {
1570 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001571 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001572 // C++ 9.6p3: A bit-field shall not be a static member.
1573 // "static member 'A' cannot be a bit-field"
1574 Diag(Loc, diag::err_static_not_bitfield)
1575 << Name << BitWidth->getSourceRange();
1576 } else if (isa<TypedefDecl>(Member)) {
1577 // "typedef member 'x' cannot be a bit-field"
1578 Diag(Loc, diag::err_typedef_not_bitfield)
1579 << Name << BitWidth->getSourceRange();
1580 } else {
1581 // A function typedef ("typedef int f(); f a;").
1582 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1583 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001584 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001585 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Chris Lattner8b963ef2009-03-05 23:01:03 +00001588 BitWidth = 0;
1589 Member->setInvalidDecl();
1590 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001591
1592 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Douglas Gregor37b372b2009-08-20 22:52:58 +00001594 // If we have declared a member function template, set the access of the
1595 // templated declaration as well.
1596 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1597 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001598 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001599
Anders Carlssonaae5af22011-01-20 04:34:22 +00001600 if (VS.isOverrideSpecified()) {
1601 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1602 if (!MD || !MD->isVirtual()) {
1603 Diag(Member->getLocStart(),
1604 diag::override_keyword_only_allowed_on_virtual_member_functions)
1605 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001606 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001607 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001608 }
1609 if (VS.isFinalSpecified()) {
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 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001615 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001616 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001617 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001618
Douglas Gregorf5251602011-03-08 17:10:18 +00001619 if (VS.getLastLocation().isValid()) {
1620 // Update the end location of a method that has a virt-specifiers.
1621 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1622 MD->setRangeEnd(VS.getLastLocation());
1623 }
1624
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001625 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001626
Douglas Gregor10bd3682008-11-17 22:58:34 +00001627 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001628
John McCallb25b2952011-02-15 07:12:36 +00001629 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001630 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001631 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001632}
1633
Richard Smith7a614d82011-06-11 17:19:42 +00001634/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001635/// in-class initializer for a non-static C++ class member, and after
1636/// instantiating an in-class initializer in a class template. Such actions
1637/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001638void
1639Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1640 Expr *InitExpr) {
1641 FieldDecl *FD = cast<FieldDecl>(D);
1642
1643 if (!InitExpr) {
1644 FD->setInvalidDecl();
1645 FD->removeInClassInitializer();
1646 return;
1647 }
1648
Peter Collingbournefef21892011-10-23 18:59:44 +00001649 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1650 FD->setInvalidDecl();
1651 FD->removeInClassInitializer();
1652 return;
1653 }
1654
Richard Smith7a614d82011-06-11 17:19:42 +00001655 ExprResult Init = InitExpr;
1656 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1657 // FIXME: if there is no EqualLoc, this is list-initialization.
1658 Init = PerformCopyInitialization(
1659 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1660 if (Init.isInvalid()) {
1661 FD->setInvalidDecl();
1662 return;
1663 }
1664
1665 CheckImplicitConversions(Init.get(), EqualLoc);
1666 }
1667
1668 // C++0x [class.base.init]p7:
1669 // The initialization of each base and member constitutes a
1670 // full-expression.
1671 Init = MaybeCreateExprWithCleanups(Init);
1672 if (Init.isInvalid()) {
1673 FD->setInvalidDecl();
1674 return;
1675 }
1676
1677 InitExpr = Init.release();
1678
1679 FD->setInClassInitializer(InitExpr);
1680}
1681
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001682/// \brief Find the direct and/or virtual base specifiers that
1683/// correspond to the given base type, for use in base initialization
1684/// within a constructor.
1685static bool FindBaseInitializer(Sema &SemaRef,
1686 CXXRecordDecl *ClassDecl,
1687 QualType BaseType,
1688 const CXXBaseSpecifier *&DirectBaseSpec,
1689 const CXXBaseSpecifier *&VirtualBaseSpec) {
1690 // First, check for a direct base class.
1691 DirectBaseSpec = 0;
1692 for (CXXRecordDecl::base_class_const_iterator Base
1693 = ClassDecl->bases_begin();
1694 Base != ClassDecl->bases_end(); ++Base) {
1695 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1696 // We found a direct base of this type. That's what we're
1697 // initializing.
1698 DirectBaseSpec = &*Base;
1699 break;
1700 }
1701 }
1702
1703 // Check for a virtual base class.
1704 // FIXME: We might be able to short-circuit this if we know in advance that
1705 // there are no virtual bases.
1706 VirtualBaseSpec = 0;
1707 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1708 // We haven't found a base yet; search the class hierarchy for a
1709 // virtual base class.
1710 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1711 /*DetectVirtual=*/false);
1712 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1713 BaseType, Paths)) {
1714 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1715 Path != Paths.end(); ++Path) {
1716 if (Path->back().Base->isVirtual()) {
1717 VirtualBaseSpec = Path->back().Base;
1718 break;
1719 }
1720 }
1721 }
1722 }
1723
1724 return DirectBaseSpec || VirtualBaseSpec;
1725}
1726
Sebastian Redl6df65482011-09-24 17:48:25 +00001727/// \brief Handle a C++ member initializer using braced-init-list syntax.
1728MemInitResult
1729Sema::ActOnMemInitializer(Decl *ConstructorD,
1730 Scope *S,
1731 CXXScopeSpec &SS,
1732 IdentifierInfo *MemberOrBase,
1733 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001734 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001735 SourceLocation IdLoc,
1736 Expr *InitList,
1737 SourceLocation EllipsisLoc) {
1738 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001739 DS, IdLoc, MultiInitializer(InitList),
1740 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001741}
1742
1743/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001744MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001745Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001746 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001747 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001748 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001749 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001750 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001751 SourceLocation IdLoc,
1752 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001753 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001754 SourceLocation RParenLoc,
1755 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001756 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001757 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1758 NumArgs, RParenLoc),
Sebastian Redl6df65482011-09-24 17:48:25 +00001759 EllipsisLoc);
1760}
1761
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001762namespace {
1763
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001764// Callback to only accept typo corrections that can be a valid C++ member
1765// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001766class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1767 public:
1768 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1769 : ClassDecl(ClassDecl) {}
1770
1771 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1772 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1773 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1774 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1775 else
1776 return isa<TypeDecl>(ND);
1777 }
1778 return false;
1779 }
1780
1781 private:
1782 CXXRecordDecl *ClassDecl;
1783};
1784
1785}
1786
Sebastian Redl6df65482011-09-24 17:48:25 +00001787/// \brief Handle a C++ member initializer.
1788MemInitResult
1789Sema::BuildMemInitializer(Decl *ConstructorD,
1790 Scope *S,
1791 CXXScopeSpec &SS,
1792 IdentifierInfo *MemberOrBase,
1793 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001794 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001795 SourceLocation IdLoc,
1796 const MultiInitializer &Args,
1797 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001798 if (!ConstructorD)
1799 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001801 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
1803 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001804 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001805 if (!Constructor) {
1806 // The user wrote a constructor initializer on a function that is
1807 // not a C++ constructor. Ignore the error for now, because we may
1808 // have more member initializers coming; we'll diagnose it just
1809 // once in ActOnMemInitializers.
1810 return true;
1811 }
1812
1813 CXXRecordDecl *ClassDecl = Constructor->getParent();
1814
1815 // C++ [class.base.init]p2:
1816 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001817 // constructor's class and, if not found in that scope, are looked
1818 // up in the scope containing the constructor's definition.
1819 // [Note: if the constructor's class contains a member with the
1820 // same name as a direct or virtual base class of the class, a
1821 // mem-initializer-id naming the member or base class and composed
1822 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001823 // mem-initializer-id for the hidden base class may be specified
1824 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001825 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001826 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001827 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001828 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001829 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001830 ValueDecl *Member;
1831 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1832 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001833 if (EllipsisLoc.isValid())
1834 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001835 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1836
1837 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001838 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001839 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001840 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001841 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001842 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001843 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001844
1845 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001846 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001847 } else if (DS.getTypeSpecType() == TST_decltype) {
1848 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001849 } else {
1850 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1851 LookupParsedName(R, S, &SS);
1852
1853 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1854 if (!TyD) {
1855 if (R.isAmbiguous()) return true;
1856
John McCallfd225442010-04-09 19:01:14 +00001857 // We don't want access-control diagnostics here.
1858 R.suppressDiagnostics();
1859
Douglas Gregor7a886e12010-01-19 06:46:48 +00001860 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1861 bool NotUnknownSpecialization = false;
1862 DeclContext *DC = computeDeclContext(SS, false);
1863 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1864 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1865
1866 if (!NotUnknownSpecialization) {
1867 // When the scope specifier can refer to a member of an unknown
1868 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001869 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1870 SS.getWithLocInContext(Context),
1871 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001872 if (BaseType.isNull())
1873 return true;
1874
Douglas Gregor7a886e12010-01-19 06:46:48 +00001875 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001876 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001877 }
1878 }
1879
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001880 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001881 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001882 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001883 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001884 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001885 &Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001886 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1887 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1888 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001889 // We have found a non-static data member with a similar
1890 // name to what was typed; complain and initialize that
1891 // member.
1892 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1893 << MemberOrBase << true << CorrectedQuotedStr
1894 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1895 Diag(Member->getLocation(), diag::note_previous_decl)
1896 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001897
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001898 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001899 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001900 const CXXBaseSpecifier *DirectBaseSpec;
1901 const CXXBaseSpecifier *VirtualBaseSpec;
1902 if (FindBaseInitializer(*this, ClassDecl,
1903 Context.getTypeDeclType(Type),
1904 DirectBaseSpec, VirtualBaseSpec)) {
1905 // We have found a direct or virtual base class with a
1906 // similar name to what was typed; complain and initialize
1907 // that base class.
1908 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001909 << MemberOrBase << false << CorrectedQuotedStr
1910 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001911
1912 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1913 : VirtualBaseSpec;
1914 Diag(BaseSpec->getSourceRange().getBegin(),
1915 diag::note_base_class_specified_here)
1916 << BaseSpec->getType()
1917 << BaseSpec->getSourceRange();
1918
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001919 TyD = Type;
1920 }
1921 }
1922 }
1923
Douglas Gregor7a886e12010-01-19 06:46:48 +00001924 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001925 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001926 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001927 return true;
1928 }
John McCall2b194412009-12-21 10:41:20 +00001929 }
1930
Douglas Gregor7a886e12010-01-19 06:46:48 +00001931 if (BaseType.isNull()) {
1932 BaseType = Context.getTypeDeclType(TyD);
1933 if (SS.isSet()) {
1934 NestedNameSpecifier *Qualifier =
1935 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001936
Douglas Gregor7a886e12010-01-19 06:46:48 +00001937 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001938 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001939 }
John McCall2b194412009-12-21 10:41:20 +00001940 }
1941 }
Mike Stump1eb44332009-09-09 15:08:12 +00001942
John McCalla93c9342009-12-07 02:54:59 +00001943 if (!TInfo)
1944 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001945
Sebastian Redl6df65482011-09-24 17:48:25 +00001946 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001947}
1948
Chandler Carruth81c64772011-09-03 01:14:15 +00001949/// Checks a member initializer expression for cases where reference (or
1950/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001951static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1952 Expr *Init,
1953 SourceLocation IdLoc) {
1954 QualType MemberTy = Member->getType();
1955
1956 // We only handle pointers and references currently.
1957 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1958 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1959 return;
1960
1961 const bool IsPointer = MemberTy->isPointerType();
1962 if (IsPointer) {
1963 if (const UnaryOperator *Op
1964 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1965 // The only case we're worried about with pointers requires taking the
1966 // address.
1967 if (Op->getOpcode() != UO_AddrOf)
1968 return;
1969
1970 Init = Op->getSubExpr();
1971 } else {
1972 // We only handle address-of expression initializers for pointers.
1973 return;
1974 }
1975 }
1976
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001977 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1978 // Taking the address of a temporary will be diagnosed as a hard error.
1979 if (IsPointer)
1980 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001981
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001982 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1983 << Member << Init->getSourceRange();
1984 } else if (const DeclRefExpr *DRE
1985 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1986 // We only warn when referring to a non-reference parameter declaration.
1987 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1988 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001989 return;
1990
1991 S.Diag(Init->getExprLoc(),
1992 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1993 : diag::warn_bind_ref_member_to_parameter)
1994 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001995 } else {
1996 // Other initializers are fine.
1997 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001998 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001999
2000 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2001 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002002}
2003
John McCallb4190042009-11-04 23:02:40 +00002004/// Checks an initializer expression for use of uninitialized fields, such as
2005/// containing the field that is being initialized. Returns true if there is an
2006/// uninitialized field was used an updates the SourceLocation parameter; false
2007/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002008static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002009 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002010 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002011 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2012
Nick Lewycky43ad1822010-06-15 07:32:55 +00002013 if (isa<CallExpr>(S)) {
2014 // Do not descend into function calls or constructors, as the use
2015 // of an uninitialized field may be valid. One would have to inspect
2016 // the contents of the function/ctor to determine if it is safe or not.
2017 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2018 // may be safe, depending on what the function/ctor does.
2019 return false;
2020 }
2021 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2022 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002023
2024 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2025 // The member expression points to a static data member.
2026 assert(VD->isStaticDataMember() &&
2027 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002028 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002029 return false;
2030 }
2031
2032 if (isa<EnumConstantDecl>(RhsField)) {
2033 // The member expression points to an enum.
2034 return false;
2035 }
2036
John McCallb4190042009-11-04 23:02:40 +00002037 if (RhsField == LhsField) {
2038 // Initializing a field with itself. Throw a warning.
2039 // But wait; there are exceptions!
2040 // Exception #1: The field may not belong to this record.
2041 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002042 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002043 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2044 // Even though the field matches, it does not belong to this record.
2045 return false;
2046 }
2047 // None of the exceptions triggered; return true to indicate an
2048 // uninitialized field was used.
2049 *L = ME->getMemberLoc();
2050 return true;
2051 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002052 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002053 // sizeof/alignof doesn't reference contents, do not warn.
2054 return false;
2055 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2056 // address-of doesn't reference contents (the pointer may be dereferenced
2057 // in the same expression but it would be rare; and weird).
2058 if (UOE->getOpcode() == UO_AddrOf)
2059 return false;
John McCallb4190042009-11-04 23:02:40 +00002060 }
John McCall7502c1d2011-02-13 04:07:26 +00002061 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002062 if (!*it) {
2063 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002064 continue;
2065 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002066 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2067 return true;
John McCallb4190042009-11-04 23:02:40 +00002068 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002069 return false;
John McCallb4190042009-11-04 23:02:40 +00002070}
2071
John McCallf312b1e2010-08-26 23:41:50 +00002072MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002073Sema::BuildMemberInitializer(ValueDecl *Member,
2074 const MultiInitializer &Args,
2075 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002076 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2077 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2078 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002079 "Member must be a FieldDecl or IndirectFieldDecl");
2080
Peter Collingbournefef21892011-10-23 18:59:44 +00002081 if (Args.DiagnoseUnexpandedParameterPack(*this))
2082 return true;
2083
Douglas Gregor464b2f02010-11-05 22:21:31 +00002084 if (Member->isInvalidDecl())
2085 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002086
John McCallb4190042009-11-04 23:02:40 +00002087 // Diagnose value-uses of fields to initialize themselves, e.g.
2088 // foo(foo)
2089 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002090 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002091 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2092 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002093 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002094 Expr *Arg = *I;
2095 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2096 Arg = DIE->getInit();
2097 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002098 // FIXME: Return true in the case when other fields are used before being
2099 // uninitialized. For example, let this field be the i'th field. When
2100 // initializing the i'th field, throw a warning if any of the >= i'th
2101 // fields are used, as they are not yet initialized.
2102 // Right now we are only handling the case where the i'th field uses
2103 // itself in its initializer.
2104 Diag(L, diag::warn_field_is_uninit);
2105 }
2106 }
2107
Sebastian Redl6df65482011-09-24 17:48:25 +00002108 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002109
Chandler Carruth894aed92010-12-06 09:23:57 +00002110 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002111 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002112 // Can't check initialization for a member of dependent type or when
2113 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002114 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002115
John McCallf85e1932011-06-15 23:02:42 +00002116 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002117 } else {
2118 // Initialize the member.
2119 InitializedEntity MemberEntity =
2120 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2121 : InitializedEntity::InitializeMember(IndirectMember, 0);
2122 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002123 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2124 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002125
Sebastian Redl6df65482011-09-24 17:48:25 +00002126 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002127 if (MemberInit.isInvalid())
2128 return true;
2129
Sebastian Redl6df65482011-09-24 17:48:25 +00002130 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002131
2132 // C++0x [class.base.init]p7:
2133 // The initialization of each base and member constitutes a
2134 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002135 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002136 if (MemberInit.isInvalid())
2137 return true;
2138
2139 // If we are in a dependent context, template instantiation will
2140 // perform this type-checking again. Just save the arguments that we
2141 // received in a ParenListExpr.
2142 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2143 // of the information that we have about the member
2144 // initializer. However, deconstructing the ASTs is a dicey process,
2145 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002146 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002147 Init = Args.CreateInitExpr(Context,
2148 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002149 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002150 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002151 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2152 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002153 }
2154
Chandler Carruth894aed92010-12-06 09:23:57 +00002155 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002156 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002157 IdLoc, Args.getStartLoc(),
2158 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002159 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002160 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002161 IdLoc, Args.getStartLoc(),
2162 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002163 }
Eli Friedman59c04372009-07-29 19:44:27 +00002164}
2165
John McCallf312b1e2010-08-26 23:41:50 +00002166MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002167Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002168 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002169 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002170 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002171 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002172 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002173 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002174 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002175
Sean Hunt41717662011-02-26 19:13:13 +00002176 // Initialize the object.
2177 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2178 QualType(ClassDecl->getTypeForDecl(), 0));
2179 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002180 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2181 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002182
Sebastian Redl6df65482011-09-24 17:48:25 +00002183 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002184 if (DelegationInit.isInvalid())
2185 return true;
2186
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002187 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2188 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002189
Sebastian Redl6df65482011-09-24 17:48:25 +00002190 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002191
2192 // C++0x [class.base.init]p7:
2193 // The initialization of each base and member constitutes a
2194 // full-expression.
2195 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2196 if (DelegationInit.isInvalid())
2197 return true;
2198
Douglas Gregor76852c22011-11-01 01:16:03 +00002199 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002200 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002201 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002202}
2203
2204MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002205Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002206 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002207 CXXRecordDecl *ClassDecl,
2208 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002209 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002210
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002211 SourceLocation BaseLoc
2212 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002213
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002214 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2215 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2216 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2217
2218 // C++ [class.base.init]p2:
2219 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002220 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002221 // of that class, the mem-initializer is ill-formed. A
2222 // mem-initializer-list can initialize a base class using any
2223 // name that denotes that base class type.
2224 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2225
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002226 if (EllipsisLoc.isValid()) {
2227 // This is a pack expansion.
2228 if (!BaseType->containsUnexpandedParameterPack()) {
2229 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002230 << SourceRange(BaseLoc, Args.getEndLoc());
2231
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002232 EllipsisLoc = SourceLocation();
2233 }
2234 } else {
2235 // Check for any unexpanded parameter packs.
2236 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2237 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002238
2239 if (Args.DiagnoseUnexpandedParameterPack(*this))
2240 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002241 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002242
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002243 // Check for direct and virtual base classes.
2244 const CXXBaseSpecifier *DirectBaseSpec = 0;
2245 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2246 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002247 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2248 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002249 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002250
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002251 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2252 VirtualBaseSpec);
2253
2254 // C++ [base.class.init]p2:
2255 // Unless the mem-initializer-id names a nonstatic data member of the
2256 // constructor's class or a direct or virtual base of that class, the
2257 // mem-initializer is ill-formed.
2258 if (!DirectBaseSpec && !VirtualBaseSpec) {
2259 // If the class has any dependent bases, then it's possible that
2260 // one of those types will resolve to the same type as
2261 // BaseType. Therefore, just treat this as a dependent base
2262 // class initialization. FIXME: Should we try to check the
2263 // initialization anyway? It seems odd.
2264 if (ClassDecl->hasAnyDependentBases())
2265 Dependent = true;
2266 else
2267 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2268 << BaseType << Context.getTypeDeclType(ClassDecl)
2269 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2270 }
2271 }
2272
2273 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002274 // Can't check initialization for a base of dependent type or when
2275 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002276 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002277
John McCallf85e1932011-06-15 23:02:42 +00002278 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Sebastian Redl6df65482011-09-24 17:48:25 +00002280 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2281 /*IsVirtual=*/false,
2282 Args.getStartLoc(), BaseInit,
2283 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002284 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002285
2286 // C++ [base.class.init]p2:
2287 // If a mem-initializer-id is ambiguous because it designates both
2288 // a direct non-virtual base class and an inherited virtual base
2289 // class, the mem-initializer is ill-formed.
2290 if (DirectBaseSpec && VirtualBaseSpec)
2291 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002292 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002293
2294 CXXBaseSpecifier *BaseSpec
2295 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2296 if (!BaseSpec)
2297 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2298
2299 // Initialize the base.
2300 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002301 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002302 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002303 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2304 Args.getEndLoc());
2305
2306 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002307 if (BaseInit.isInvalid())
2308 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002309
Sebastian Redl6df65482011-09-24 17:48:25 +00002310 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2311
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002312 // C++0x [class.base.init]p7:
2313 // The initialization of each base and member constitutes a
2314 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002315 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002316 if (BaseInit.isInvalid())
2317 return true;
2318
2319 // If we are in a dependent context, template instantiation will
2320 // perform this type-checking again. Just save the arguments that we
2321 // received in a ParenListExpr.
2322 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2323 // of the information that we have about the base
2324 // initializer. However, deconstructing the ASTs is a dicey process,
2325 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002326 if (CurContext->isDependentContext())
2327 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002328
Sean Huntcbb67482011-01-08 20:30:50 +00002329 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002330 BaseSpec->isVirtual(),
2331 Args.getStartLoc(),
2332 BaseInit.takeAs<Expr>(),
2333 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002334}
2335
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002336// Create a static_cast\<T&&>(expr).
2337static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2338 QualType ExprType = E->getType();
2339 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2340 SourceLocation ExprLoc = E->getLocStart();
2341 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2342 TargetType, ExprLoc);
2343
2344 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2345 SourceRange(ExprLoc, ExprLoc),
2346 E->getSourceRange()).take();
2347}
2348
Anders Carlssone5ef7402010-04-23 03:10:23 +00002349/// ImplicitInitializerKind - How an implicit base or member initializer should
2350/// initialize its base or member.
2351enum ImplicitInitializerKind {
2352 IIK_Default,
2353 IIK_Copy,
2354 IIK_Move
2355};
2356
Anders Carlssondefefd22010-04-23 02:00:02 +00002357static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002358BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002359 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002360 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002361 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002362 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002363 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002364 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2365 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002366
John McCall60d7b3a2010-08-24 06:29:42 +00002367 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002368
2369 switch (ImplicitInitKind) {
2370 case IIK_Default: {
2371 InitializationKind InitKind
2372 = InitializationKind::CreateDefault(Constructor->getLocation());
2373 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2374 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002375 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002376 break;
2377 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002378
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002379 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002380 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002381 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002382 ParmVarDecl *Param = Constructor->getParamDecl(0);
2383 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002384
2385 SemaRef.MarkDeclarationReferenced(Constructor->getLocation(), Param);
2386
Anders Carlssone5ef7402010-04-23 03:10:23 +00002387 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002388 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002389 Constructor->getLocation(), ParamType,
2390 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002391
Anders Carlssonc7957502010-04-24 22:02:54 +00002392 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002393 QualType ArgTy =
2394 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2395 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002396
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002397 if (Moving) {
2398 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2399 }
2400
John McCallf871d0c2010-08-07 06:22:56 +00002401 CXXCastPath BasePath;
2402 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002403 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2404 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002405 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002406 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002407
Anders Carlssone5ef7402010-04-23 03:10:23 +00002408 InitializationKind InitKind
2409 = InitializationKind::CreateDirect(Constructor->getLocation(),
2410 SourceLocation(), SourceLocation());
2411 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2412 &CopyCtorArg, 1);
2413 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002414 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002415 break;
2416 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002417 }
John McCall9ae2f072010-08-23 23:25:46 +00002418
Douglas Gregor53c374f2010-12-07 00:41:46 +00002419 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002420 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002421 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002422
Anders Carlssondefefd22010-04-23 02:00:02 +00002423 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002424 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002425 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2426 SourceLocation()),
2427 BaseSpec->isVirtual(),
2428 SourceLocation(),
2429 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002430 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002431 SourceLocation());
2432
Anders Carlssondefefd22010-04-23 02:00:02 +00002433 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002434}
2435
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002436static bool RefersToRValueRef(Expr *MemRef) {
2437 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2438 return Referenced->getType()->isRValueReferenceType();
2439}
2440
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002441static bool
2442BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002443 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002444 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002445 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002446 if (Field->isInvalidDecl())
2447 return true;
2448
Chandler Carruthf186b542010-06-29 23:50:44 +00002449 SourceLocation Loc = Constructor->getLocation();
2450
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002451 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2452 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002453 ParmVarDecl *Param = Constructor->getParamDecl(0);
2454 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002455
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002456 SemaRef.MarkDeclarationReferenced(Constructor->getLocation(), Param);
2457
John McCallb77115d2011-06-17 00:18:42 +00002458 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002459 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2460 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002461
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002462 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002463 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002464 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002465
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002466 if (Moving) {
2467 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2468 }
2469
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002470 // Build a reference to this field within the parameter.
2471 CXXScopeSpec SS;
2472 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2473 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002474 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2475 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002476 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002477 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002478 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002479 ParamType, Loc,
2480 /*IsArrow=*/false,
2481 SS,
2482 /*FirstQualifierInScope=*/0,
2483 MemberLookup,
2484 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002485 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002486 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002487
2488 // C++11 [class.copy]p15:
2489 // - if a member m has rvalue reference type T&&, it is direct-initialized
2490 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002491 if (RefersToRValueRef(CtorArg.get())) {
2492 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002493 }
2494
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002495 // When the field we are copying is an array, create index variables for
2496 // each dimension of the array. We use these index variables to subscript
2497 // the source array, and other clients (e.g., CodeGen) will perform the
2498 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002499 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002500 QualType BaseType = Field->getType();
2501 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002502 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002503 while (const ConstantArrayType *Array
2504 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002505 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002506 // Create the iteration variable for this array index.
2507 IdentifierInfo *IterationVarName = 0;
2508 {
2509 llvm::SmallString<8> Str;
2510 llvm::raw_svector_ostream OS(Str);
2511 OS << "__i" << IndexVariables.size();
2512 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2513 }
2514 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002515 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002516 IterationVarName, SizeType,
2517 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002518 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002519 IndexVariables.push_back(IterationVar);
2520
2521 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002522 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002523 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002524 assert(!IterationVarRef.isInvalid() &&
2525 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002526 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2527 assert(!IterationVarRef.isInvalid() &&
2528 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002529
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002530 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002531 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002532 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002533 Loc);
2534 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002535 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002536
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002537 BaseType = Array->getElementType();
2538 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002539
2540 // The array subscript expression is an lvalue, which is wrong for moving.
2541 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002542 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002543
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002544 // Construct the entity that we will be initializing. For an array, this
2545 // will be first element in the array, which may require several levels
2546 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002547 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002548 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002549 if (Indirect)
2550 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2551 else
2552 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002553 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2554 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2555 0,
2556 Entities.back()));
2557
2558 // Direct-initialize to use the copy constructor.
2559 InitializationKind InitKind =
2560 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2561
Sebastian Redl74e611a2011-09-04 18:14:28 +00002562 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002563 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002564 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002565
John McCall60d7b3a2010-08-24 06:29:42 +00002566 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002567 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002568 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002569 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002570 if (MemberInit.isInvalid())
2571 return true;
2572
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002573 if (Indirect) {
2574 assert(IndexVariables.size() == 0 &&
2575 "Indirect field improperly initialized");
2576 CXXMemberInit
2577 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2578 Loc, Loc,
2579 MemberInit.takeAs<Expr>(),
2580 Loc);
2581 } else
2582 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2583 Loc, MemberInit.takeAs<Expr>(),
2584 Loc,
2585 IndexVariables.data(),
2586 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002587 return false;
2588 }
2589
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002590 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2591
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002592 QualType FieldBaseElementType =
2593 SemaRef.Context.getBaseElementType(Field->getType());
2594
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002595 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002596 InitializedEntity InitEntity
2597 = Indirect? InitializedEntity::InitializeMember(Indirect)
2598 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002599 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002600 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002601
2602 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002603 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002604 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002605
Douglas Gregor53c374f2010-12-07 00:41:46 +00002606 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002607 if (MemberInit.isInvalid())
2608 return true;
2609
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002610 if (Indirect)
2611 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2612 Indirect, Loc,
2613 Loc,
2614 MemberInit.get(),
2615 Loc);
2616 else
2617 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2618 Field, Loc, Loc,
2619 MemberInit.get(),
2620 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002621 return false;
2622 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002623
Sean Hunt1f2f3842011-05-17 00:19:05 +00002624 if (!Field->getParent()->isUnion()) {
2625 if (FieldBaseElementType->isReferenceType()) {
2626 SemaRef.Diag(Constructor->getLocation(),
2627 diag::err_uninitialized_member_in_ctor)
2628 << (int)Constructor->isImplicit()
2629 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2630 << 0 << Field->getDeclName();
2631 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2632 return true;
2633 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002634
Sean Hunt1f2f3842011-05-17 00:19:05 +00002635 if (FieldBaseElementType.isConstQualified()) {
2636 SemaRef.Diag(Constructor->getLocation(),
2637 diag::err_uninitialized_member_in_ctor)
2638 << (int)Constructor->isImplicit()
2639 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2640 << 1 << Field->getDeclName();
2641 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2642 return true;
2643 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002644 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002645
John McCallf85e1932011-06-15 23:02:42 +00002646 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2647 FieldBaseElementType->isObjCRetainableType() &&
2648 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2649 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2650 // Instant objects:
2651 // Default-initialize Objective-C pointers to NULL.
2652 CXXMemberInit
2653 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2654 Loc, Loc,
2655 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2656 Loc);
2657 return false;
2658 }
2659
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002660 // Nothing to initialize.
2661 CXXMemberInit = 0;
2662 return false;
2663}
John McCallf1860e52010-05-20 23:23:51 +00002664
2665namespace {
2666struct BaseAndFieldInfo {
2667 Sema &S;
2668 CXXConstructorDecl *Ctor;
2669 bool AnyErrorsInInits;
2670 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002671 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002672 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002673
2674 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2675 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002676 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2677 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002678 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002679 else if (Generated && Ctor->isMoveConstructor())
2680 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002681 else
2682 IIK = IIK_Default;
2683 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002684
2685 bool isImplicitCopyOrMove() const {
2686 switch (IIK) {
2687 case IIK_Copy:
2688 case IIK_Move:
2689 return true;
2690
2691 case IIK_Default:
2692 return false;
2693 }
David Blaikie30263482012-01-20 21:50:17 +00002694
2695 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002696 }
John McCallf1860e52010-05-20 23:23:51 +00002697};
2698}
2699
Richard Smitha4950662011-09-19 13:34:43 +00002700/// \brief Determine whether the given indirect field declaration is somewhere
2701/// within an anonymous union.
2702static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2703 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2704 CEnd = F->chain_end();
2705 C != CEnd; ++C)
2706 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2707 if (Record->isUnion())
2708 return true;
2709
2710 return false;
2711}
2712
Douglas Gregorddb21472011-11-02 23:04:16 +00002713/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2714/// array type.
2715static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2716 if (T->isIncompleteArrayType())
2717 return true;
2718
2719 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2720 if (!ArrayT->getSize())
2721 return true;
2722
2723 T = ArrayT->getElementType();
2724 }
2725
2726 return false;
2727}
2728
Richard Smith7a614d82011-06-11 17:19:42 +00002729static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002730 FieldDecl *Field,
2731 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002732
Chandler Carruthe861c602010-06-30 02:59:29 +00002733 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002734 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002735 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002736 return false;
2737 }
2738
Richard Smith7a614d82011-06-11 17:19:42 +00002739 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2740 // has a brace-or-equal-initializer, the entity is initialized as specified
2741 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002742 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002743 CXXCtorInitializer *Init;
2744 if (Indirect)
2745 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2746 SourceLocation(),
2747 SourceLocation(), 0,
2748 SourceLocation());
2749 else
2750 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2751 SourceLocation(),
2752 SourceLocation(), 0,
2753 SourceLocation());
2754 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002755 return false;
2756 }
2757
Richard Smithc115f632011-09-18 11:14:50 +00002758 // Don't build an implicit initializer for union members if none was
2759 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002760 if (Field->getParent()->isUnion() ||
2761 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002762 return false;
2763
Douglas Gregorddb21472011-11-02 23:04:16 +00002764 // Don't initialize incomplete or zero-length arrays.
2765 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2766 return false;
2767
John McCallf1860e52010-05-20 23:23:51 +00002768 // Don't try to build an implicit initializer if there were semantic
2769 // errors in any of the initializers (and therefore we might be
2770 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002771 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002772 return false;
2773
Sean Huntcbb67482011-01-08 20:30:50 +00002774 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002775 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2776 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002777 return true;
John McCallf1860e52010-05-20 23:23:51 +00002778
Francois Pichet00eb3f92010-12-04 09:14:42 +00002779 if (Init)
2780 Info.AllToInit.push_back(Init);
2781
John McCallf1860e52010-05-20 23:23:51 +00002782 return false;
2783}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002784
2785bool
2786Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2787 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002788 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002789 Constructor->setNumCtorInitializers(1);
2790 CXXCtorInitializer **initializer =
2791 new (Context) CXXCtorInitializer*[1];
2792 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2793 Constructor->setCtorInitializers(initializer);
2794
Sean Huntb76af9c2011-05-03 23:05:34 +00002795 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2796 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2797 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2798 }
2799
Sean Huntc1598702011-05-05 00:05:47 +00002800 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002801
Sean Hunt059ce0d2011-05-01 07:04:31 +00002802 return false;
2803}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002804
John McCallb77115d2011-06-17 00:18:42 +00002805bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2806 CXXCtorInitializer **Initializers,
2807 unsigned NumInitializers,
2808 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002809 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002810 // Just store the initializers as written, they will be checked during
2811 // instantiation.
2812 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002813 Constructor->setNumCtorInitializers(NumInitializers);
2814 CXXCtorInitializer **baseOrMemberInitializers =
2815 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002816 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002817 NumInitializers * sizeof(CXXCtorInitializer*));
2818 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002819 }
2820
2821 return false;
2822 }
2823
John McCallf1860e52010-05-20 23:23:51 +00002824 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002825
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002826 // We need to build the initializer AST according to order of construction
2827 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002828 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002829 if (!ClassDecl)
2830 return true;
2831
Eli Friedman80c30da2009-11-09 19:20:36 +00002832 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002834 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002835 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002836
2837 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002838 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002839 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002840 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002841 }
2842
Anders Carlsson711f34a2010-04-21 19:52:01 +00002843 // Keep track of the direct virtual bases.
2844 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2845 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2846 E = ClassDecl->bases_end(); I != E; ++I) {
2847 if (I->isVirtual())
2848 DirectVBases.insert(I);
2849 }
2850
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002851 // Push virtual bases before others.
2852 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2853 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2854
Sean Huntcbb67482011-01-08 20:30:50 +00002855 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002856 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2857 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002858 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002859 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002860 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002861 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002862 VBase, IsInheritedVirtualBase,
2863 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002864 HadError = true;
2865 continue;
2866 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002867
John McCallf1860e52010-05-20 23:23:51 +00002868 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002869 }
2870 }
Mike Stump1eb44332009-09-09 15:08:12 +00002871
John McCallf1860e52010-05-20 23:23:51 +00002872 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002873 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2874 E = ClassDecl->bases_end(); Base != E; ++Base) {
2875 // Virtuals are in the virtual base list and already constructed.
2876 if (Base->isVirtual())
2877 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Sean Huntcbb67482011-01-08 20:30:50 +00002879 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002880 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2881 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002882 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002883 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002884 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002885 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002886 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002887 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002888 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002889 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002890
John McCallf1860e52010-05-20 23:23:51 +00002891 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002892 }
2893 }
Mike Stump1eb44332009-09-09 15:08:12 +00002894
John McCallf1860e52010-05-20 23:23:51 +00002895 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002896 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2897 MemEnd = ClassDecl->decls_end();
2898 Mem != MemEnd; ++Mem) {
2899 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002900 // C++ [class.bit]p2:
2901 // A declaration for a bit-field that omits the identifier declares an
2902 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2903 // initialized.
2904 if (F->isUnnamedBitfield())
2905 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002906
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002907 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002908 // handle anonymous struct/union fields based on their individual
2909 // indirect fields.
2910 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2911 continue;
2912
2913 if (CollectFieldInitializer(*this, Info, F))
2914 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002915 continue;
2916 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002917
2918 // Beyond this point, we only consider default initialization.
2919 if (Info.IIK != IIK_Default)
2920 continue;
2921
2922 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2923 if (F->getType()->isIncompleteArrayType()) {
2924 assert(ClassDecl->hasFlexibleArrayMember() &&
2925 "Incomplete array type is not valid");
2926 continue;
2927 }
2928
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002929 // Initialize each field of an anonymous struct individually.
2930 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2931 HadError = true;
2932
2933 continue;
2934 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002935 }
Mike Stump1eb44332009-09-09 15:08:12 +00002936
John McCallf1860e52010-05-20 23:23:51 +00002937 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002938 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002939 Constructor->setNumCtorInitializers(NumInitializers);
2940 CXXCtorInitializer **baseOrMemberInitializers =
2941 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002942 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002943 NumInitializers * sizeof(CXXCtorInitializer*));
2944 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002945
John McCallef027fe2010-03-16 21:39:52 +00002946 // Constructors implicitly reference the base and member
2947 // destructors.
2948 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2949 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002950 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002951
2952 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002953}
2954
Eli Friedman6347f422009-07-21 19:28:10 +00002955static void *GetKeyForTopLevelField(FieldDecl *Field) {
2956 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002957 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002958 if (RT->getDecl()->isAnonymousStructOrUnion())
2959 return static_cast<void *>(RT->getDecl());
2960 }
2961 return static_cast<void *>(Field);
2962}
2963
Anders Carlssonea356fb2010-04-02 05:42:15 +00002964static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002965 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002966}
2967
Anders Carlssonea356fb2010-04-02 05:42:15 +00002968static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002969 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002970 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002971 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002972
Eli Friedman6347f422009-07-21 19:28:10 +00002973 // For fields injected into the class via declaration of an anonymous union,
2974 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002975 FieldDecl *Field = Member->getAnyMember();
2976
John McCall3c3ccdb2010-04-10 09:28:51 +00002977 // If the field is a member of an anonymous struct or union, our key
2978 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002979 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002980 if (RD->isAnonymousStructOrUnion()) {
2981 while (true) {
2982 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2983 if (Parent->isAnonymousStructOrUnion())
2984 RD = Parent;
2985 else
2986 break;
2987 }
2988
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002989 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002990 }
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002992 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002993}
2994
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002995static void
2996DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002997 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002998 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002999 unsigned NumInits) {
3000 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003001 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003003 // Don't check initializers order unless the warning is enabled at the
3004 // location of at least one initializer.
3005 bool ShouldCheckOrder = false;
3006 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003007 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003008 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3009 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003010 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003011 ShouldCheckOrder = true;
3012 break;
3013 }
3014 }
3015 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003016 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003017
John McCalld6ca8da2010-04-10 07:37:23 +00003018 // Build the list of bases and members in the order that they'll
3019 // actually be initialized. The explicit initializers should be in
3020 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003021 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Anders Carlsson071d6102010-04-02 03:38:04 +00003023 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3024
John McCalld6ca8da2010-04-10 07:37:23 +00003025 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003026 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003027 ClassDecl->vbases_begin(),
3028 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003029 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003030
John McCalld6ca8da2010-04-10 07:37:23 +00003031 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003032 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003033 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003034 if (Base->isVirtual())
3035 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003036 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003037 }
Mike Stump1eb44332009-09-09 15:08:12 +00003038
John McCalld6ca8da2010-04-10 07:37:23 +00003039 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003040 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003041 E = ClassDecl->field_end(); Field != E; ++Field) {
3042 if (Field->isUnnamedBitfield())
3043 continue;
3044
John McCalld6ca8da2010-04-10 07:37:23 +00003045 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003046 }
3047
John McCalld6ca8da2010-04-10 07:37:23 +00003048 unsigned NumIdealInits = IdealInitKeys.size();
3049 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003050
Sean Huntcbb67482011-01-08 20:30:50 +00003051 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003052 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003053 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003054 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003055
3056 // Scan forward to try to find this initializer in the idealized
3057 // initializers list.
3058 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3059 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003060 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003061
3062 // If we didn't find this initializer, it must be because we
3063 // scanned past it on a previous iteration. That can only
3064 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003065 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003066 Sema::SemaDiagnosticBuilder D =
3067 SemaRef.Diag(PrevInit->getSourceLocation(),
3068 diag::warn_initializer_out_of_order);
3069
Francois Pichet00eb3f92010-12-04 09:14:42 +00003070 if (PrevInit->isAnyMemberInitializer())
3071 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003072 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003073 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003074
Francois Pichet00eb3f92010-12-04 09:14:42 +00003075 if (Init->isAnyMemberInitializer())
3076 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003077 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003078 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003079
3080 // Move back to the initializer's location in the ideal list.
3081 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3082 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003083 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003084
3085 assert(IdealIndex != NumIdealInits &&
3086 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003087 }
John McCalld6ca8da2010-04-10 07:37:23 +00003088
3089 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003090 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003091}
3092
John McCall3c3ccdb2010-04-10 09:28:51 +00003093namespace {
3094bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003095 CXXCtorInitializer *Init,
3096 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003097 if (!PrevInit) {
3098 PrevInit = Init;
3099 return false;
3100 }
3101
3102 if (FieldDecl *Field = Init->getMember())
3103 S.Diag(Init->getSourceLocation(),
3104 diag::err_multiple_mem_initialization)
3105 << Field->getDeclName()
3106 << Init->getSourceRange();
3107 else {
John McCallf4c73712011-01-19 06:33:43 +00003108 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003109 assert(BaseClass && "neither field nor base");
3110 S.Diag(Init->getSourceLocation(),
3111 diag::err_multiple_base_initialization)
3112 << QualType(BaseClass, 0)
3113 << Init->getSourceRange();
3114 }
3115 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3116 << 0 << PrevInit->getSourceRange();
3117
3118 return true;
3119}
3120
Sean Huntcbb67482011-01-08 20:30:50 +00003121typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003122typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3123
3124bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003125 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003126 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003127 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003128 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003129 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003130
3131 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003132 if (Parent->isUnion()) {
3133 UnionEntry &En = Unions[Parent];
3134 if (En.first && En.first != Child) {
3135 S.Diag(Init->getSourceLocation(),
3136 diag::err_multiple_mem_union_initialization)
3137 << Field->getDeclName()
3138 << Init->getSourceRange();
3139 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3140 << 0 << En.second->getSourceRange();
3141 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003142 }
3143 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003144 En.first = Child;
3145 En.second = Init;
3146 }
David Blaikie6fe29652011-11-17 06:01:57 +00003147 if (!Parent->isAnonymousStructOrUnion())
3148 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003149 }
3150
3151 Child = Parent;
3152 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003153 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003154
3155 return false;
3156}
3157}
3158
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003159/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003160void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003161 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003162 CXXCtorInitializer **meminits,
3163 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003164 bool AnyErrors) {
3165 if (!ConstructorDecl)
3166 return;
3167
3168 AdjustDeclIfTemplate(ConstructorDecl);
3169
3170 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003171 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003172
3173 if (!Constructor) {
3174 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3175 return;
3176 }
3177
Sean Huntcbb67482011-01-08 20:30:50 +00003178 CXXCtorInitializer **MemInits =
3179 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003180
3181 // Mapping for the duplicate initializers check.
3182 // For member initializers, this is keyed with a FieldDecl*.
3183 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003184 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003185
3186 // Mapping for the inconsistent anonymous-union initializers check.
3187 RedundantUnionMap MemberUnions;
3188
Anders Carlssonea356fb2010-04-02 05:42:15 +00003189 bool HadError = false;
3190 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003191 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003192
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003193 // Set the source order index.
3194 Init->setSourceOrder(i);
3195
Francois Pichet00eb3f92010-12-04 09:14:42 +00003196 if (Init->isAnyMemberInitializer()) {
3197 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003198 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3199 CheckRedundantUnionInit(*this, Init, MemberUnions))
3200 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003201 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003202 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3203 if (CheckRedundantInit(*this, Init, Members[Key]))
3204 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003205 } else {
3206 assert(Init->isDelegatingInitializer());
3207 // This must be the only initializer
3208 if (i != 0 || NumMemInits > 1) {
3209 Diag(MemInits[0]->getSourceLocation(),
3210 diag::err_delegating_initializer_alone)
3211 << MemInits[0]->getSourceRange();
3212 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003213 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003214 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003215 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003216 // Return immediately as the initializer is set.
3217 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003218 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003219 }
3220
Anders Carlssonea356fb2010-04-02 05:42:15 +00003221 if (HadError)
3222 return;
3223
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003224 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003225
Sean Huntcbb67482011-01-08 20:30:50 +00003226 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003227}
3228
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003229void
John McCallef027fe2010-03-16 21:39:52 +00003230Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3231 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003232 // Ignore dependent contexts. Also ignore unions, since their members never
3233 // have destructors implicitly called.
3234 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003235 return;
John McCall58e6f342010-03-16 05:22:47 +00003236
3237 // FIXME: all the access-control diagnostics are positioned on the
3238 // field/base declaration. That's probably good; that said, the
3239 // user might reasonably want to know why the destructor is being
3240 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003241
Anders Carlsson9f853df2009-11-17 04:44:12 +00003242 // Non-static data members.
3243 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3244 E = ClassDecl->field_end(); I != E; ++I) {
3245 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003246 if (Field->isInvalidDecl())
3247 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003248
3249 // Don't destroy incomplete or zero-length arrays.
3250 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3251 continue;
3252
Anders Carlsson9f853df2009-11-17 04:44:12 +00003253 QualType FieldType = Context.getBaseElementType(Field->getType());
3254
3255 const RecordType* RT = FieldType->getAs<RecordType>();
3256 if (!RT)
3257 continue;
3258
3259 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003260 if (FieldClassDecl->isInvalidDecl())
3261 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003262 if (FieldClassDecl->hasTrivialDestructor())
3263 continue;
3264
Douglas Gregordb89f282010-07-01 22:47:18 +00003265 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003266 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003267 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003268 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003269 << Field->getDeclName()
3270 << FieldType);
3271
John McCallef027fe2010-03-16 21:39:52 +00003272 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003273 }
3274
John McCall58e6f342010-03-16 05:22:47 +00003275 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3276
Anders Carlsson9f853df2009-11-17 04:44:12 +00003277 // Bases.
3278 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3279 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003280 // Bases are always records in a well-formed non-dependent class.
3281 const RecordType *RT = Base->getType()->getAs<RecordType>();
3282
3283 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003284 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003285 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003286
John McCall58e6f342010-03-16 05:22:47 +00003287 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003288 // If our base class is invalid, we probably can't get its dtor anyway.
3289 if (BaseClassDecl->isInvalidDecl())
3290 continue;
3291 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003292 if (BaseClassDecl->hasTrivialDestructor())
3293 continue;
John McCall58e6f342010-03-16 05:22:47 +00003294
Douglas Gregordb89f282010-07-01 22:47:18 +00003295 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003296 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003297
3298 // FIXME: caret should be on the start of the class name
3299 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003300 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003301 << Base->getType()
3302 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003303
John McCallef027fe2010-03-16 21:39:52 +00003304 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003305 }
3306
3307 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003308 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3309 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003310
3311 // Bases are always records in a well-formed non-dependent class.
3312 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3313
3314 // Ignore direct virtual bases.
3315 if (DirectVirtualBases.count(RT))
3316 continue;
3317
John McCall58e6f342010-03-16 05:22:47 +00003318 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003319 // If our base class is invalid, we probably can't get its dtor anyway.
3320 if (BaseClassDecl->isInvalidDecl())
3321 continue;
3322 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003323 if (BaseClassDecl->hasTrivialDestructor())
3324 continue;
John McCall58e6f342010-03-16 05:22:47 +00003325
Douglas Gregordb89f282010-07-01 22:47:18 +00003326 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003327 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003328 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003329 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003330 << VBase->getType());
3331
John McCallef027fe2010-03-16 21:39:52 +00003332 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003333 }
3334}
3335
John McCalld226f652010-08-21 09:40:31 +00003336void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003337 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003338 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Mike Stump1eb44332009-09-09 15:08:12 +00003340 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003341 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003342 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003343}
3344
Mike Stump1eb44332009-09-09 15:08:12 +00003345bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003346 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003347 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003348 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003349 else
John McCall94c3b562010-08-18 09:41:07 +00003350 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003351}
3352
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003353bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003354 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003355 if (!getLangOptions().CPlusPlus)
3356 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Anders Carlsson11f21a02009-03-23 19:10:31 +00003358 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003359 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Ted Kremenek6217b802009-07-29 21:53:49 +00003361 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003362 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003363 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003364 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003365
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003366 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003367 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003368 }
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Ted Kremenek6217b802009-07-29 21:53:49 +00003370 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003371 if (!RT)
3372 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003373
John McCall86ff3082010-02-04 22:26:26 +00003374 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003375
John McCall94c3b562010-08-18 09:41:07 +00003376 // We can't answer whether something is abstract until it has a
3377 // definition. If it's currently being defined, we'll walk back
3378 // over all the declarations when we have a full definition.
3379 const CXXRecordDecl *Def = RD->getDefinition();
3380 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003381 return false;
3382
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003383 if (!RD->isAbstract())
3384 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003386 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003387 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003388
John McCall94c3b562010-08-18 09:41:07 +00003389 return true;
3390}
3391
3392void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3393 // Check if we've already emitted the list of pure virtual functions
3394 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003395 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003396 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003398 CXXFinalOverriderMap FinalOverriders;
3399 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003401 // Keep a set of seen pure methods so we won't diagnose the same method
3402 // more than once.
3403 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3404
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003405 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3406 MEnd = FinalOverriders.end();
3407 M != MEnd;
3408 ++M) {
3409 for (OverridingMethods::iterator SO = M->second.begin(),
3410 SOEnd = M->second.end();
3411 SO != SOEnd; ++SO) {
3412 // C++ [class.abstract]p4:
3413 // A class is abstract if it contains or inherits at least one
3414 // pure virtual function for which the final overrider is pure
3415 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003416
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003417 //
3418 if (SO->second.size() != 1)
3419 continue;
3420
3421 if (!SO->second.front().Method->isPure())
3422 continue;
3423
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003424 if (!SeenPureMethods.insert(SO->second.front().Method))
3425 continue;
3426
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003427 Diag(SO->second.front().Method->getLocation(),
3428 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003429 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003430 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003431 }
3432
3433 if (!PureVirtualClassDiagSet)
3434 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3435 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003436}
3437
Anders Carlsson8211eff2009-03-24 01:19:16 +00003438namespace {
John McCall94c3b562010-08-18 09:41:07 +00003439struct AbstractUsageInfo {
3440 Sema &S;
3441 CXXRecordDecl *Record;
3442 CanQualType AbstractType;
3443 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003444
John McCall94c3b562010-08-18 09:41:07 +00003445 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3446 : S(S), Record(Record),
3447 AbstractType(S.Context.getCanonicalType(
3448 S.Context.getTypeDeclType(Record))),
3449 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003450
John McCall94c3b562010-08-18 09:41:07 +00003451 void DiagnoseAbstractType() {
3452 if (Invalid) return;
3453 S.DiagnoseAbstractType(Record);
3454 Invalid = true;
3455 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003456
John McCall94c3b562010-08-18 09:41:07 +00003457 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3458};
3459
3460struct CheckAbstractUsage {
3461 AbstractUsageInfo &Info;
3462 const NamedDecl *Ctx;
3463
3464 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3465 : Info(Info), Ctx(Ctx) {}
3466
3467 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3468 switch (TL.getTypeLocClass()) {
3469#define ABSTRACT_TYPELOC(CLASS, PARENT)
3470#define TYPELOC(CLASS, PARENT) \
3471 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3472#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003473 }
John McCall94c3b562010-08-18 09:41:07 +00003474 }
Mike Stump1eb44332009-09-09 15:08:12 +00003475
John McCall94c3b562010-08-18 09:41:07 +00003476 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3477 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3478 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003479 if (!TL.getArg(I))
3480 continue;
3481
John McCall94c3b562010-08-18 09:41:07 +00003482 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3483 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003484 }
John McCall94c3b562010-08-18 09:41:07 +00003485 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003486
John McCall94c3b562010-08-18 09:41:07 +00003487 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3488 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3489 }
Mike Stump1eb44332009-09-09 15:08:12 +00003490
John McCall94c3b562010-08-18 09:41:07 +00003491 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3492 // Visit the type parameters from a permissive context.
3493 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3494 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3495 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3496 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3497 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3498 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003499 }
John McCall94c3b562010-08-18 09:41:07 +00003500 }
Mike Stump1eb44332009-09-09 15:08:12 +00003501
John McCall94c3b562010-08-18 09:41:07 +00003502 // Visit pointee types from a permissive context.
3503#define CheckPolymorphic(Type) \
3504 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3505 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3506 }
3507 CheckPolymorphic(PointerTypeLoc)
3508 CheckPolymorphic(ReferenceTypeLoc)
3509 CheckPolymorphic(MemberPointerTypeLoc)
3510 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003511 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003512
John McCall94c3b562010-08-18 09:41:07 +00003513 /// Handle all the types we haven't given a more specific
3514 /// implementation for above.
3515 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3516 // Every other kind of type that we haven't called out already
3517 // that has an inner type is either (1) sugar or (2) contains that
3518 // inner type in some way as a subobject.
3519 if (TypeLoc Next = TL.getNextTypeLoc())
3520 return Visit(Next, Sel);
3521
3522 // If there's no inner type and we're in a permissive context,
3523 // don't diagnose.
3524 if (Sel == Sema::AbstractNone) return;
3525
3526 // Check whether the type matches the abstract type.
3527 QualType T = TL.getType();
3528 if (T->isArrayType()) {
3529 Sel = Sema::AbstractArrayType;
3530 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003531 }
John McCall94c3b562010-08-18 09:41:07 +00003532 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3533 if (CT != Info.AbstractType) return;
3534
3535 // It matched; do some magic.
3536 if (Sel == Sema::AbstractArrayType) {
3537 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3538 << T << TL.getSourceRange();
3539 } else {
3540 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3541 << Sel << T << TL.getSourceRange();
3542 }
3543 Info.DiagnoseAbstractType();
3544 }
3545};
3546
3547void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3548 Sema::AbstractDiagSelID Sel) {
3549 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3550}
3551
3552}
3553
3554/// Check for invalid uses of an abstract type in a method declaration.
3555static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3556 CXXMethodDecl *MD) {
3557 // No need to do the check on definitions, which require that
3558 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003559 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003560 return;
3561
3562 // For safety's sake, just ignore it if we don't have type source
3563 // information. This should never happen for non-implicit methods,
3564 // but...
3565 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3566 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3567}
3568
3569/// Check for invalid uses of an abstract type within a class definition.
3570static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3571 CXXRecordDecl *RD) {
3572 for (CXXRecordDecl::decl_iterator
3573 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3574 Decl *D = *I;
3575 if (D->isImplicit()) continue;
3576
3577 // Methods and method templates.
3578 if (isa<CXXMethodDecl>(D)) {
3579 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3580 } else if (isa<FunctionTemplateDecl>(D)) {
3581 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3582 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3583
3584 // Fields and static variables.
3585 } else if (isa<FieldDecl>(D)) {
3586 FieldDecl *FD = cast<FieldDecl>(D);
3587 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3588 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3589 } else if (isa<VarDecl>(D)) {
3590 VarDecl *VD = cast<VarDecl>(D);
3591 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3592 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3593
3594 // Nested classes and class templates.
3595 } else if (isa<CXXRecordDecl>(D)) {
3596 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3597 } else if (isa<ClassTemplateDecl>(D)) {
3598 CheckAbstractClassUsage(Info,
3599 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3600 }
3601 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003602}
3603
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003604/// \brief Perform semantic checks on a class definition that has been
3605/// completing, introducing implicitly-declared members, checking for
3606/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003607void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003608 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003609 return;
3610
John McCall94c3b562010-08-18 09:41:07 +00003611 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3612 AbstractUsageInfo Info(*this, Record);
3613 CheckAbstractClassUsage(Info, Record);
3614 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003615
3616 // If this is not an aggregate type and has no user-declared constructor,
3617 // complain about any non-static data members of reference or const scalar
3618 // type, since they will never get initializers.
3619 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3620 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3621 bool Complained = false;
3622 for (RecordDecl::field_iterator F = Record->field_begin(),
3623 FEnd = Record->field_end();
3624 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003625 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003626 continue;
3627
Douglas Gregor325e5932010-04-15 00:00:53 +00003628 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003629 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003630 if (!Complained) {
3631 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3632 << Record->getTagKind() << Record;
3633 Complained = true;
3634 }
3635
3636 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3637 << F->getType()->isReferenceType()
3638 << F->getDeclName();
3639 }
3640 }
3641 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003642
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003643 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003644 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003645
3646 if (Record->getIdentifier()) {
3647 // C++ [class.mem]p13:
3648 // If T is the name of a class, then each of the following shall have a
3649 // name different from T:
3650 // - every member of every anonymous union that is a member of class T.
3651 //
3652 // C++ [class.mem]p14:
3653 // In addition, if class T has a user-declared constructor (12.1), every
3654 // non-static data member of class T shall have a name different from T.
3655 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003656 R.first != R.second; ++R.first) {
3657 NamedDecl *D = *R.first;
3658 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3659 isa<IndirectFieldDecl>(D)) {
3660 Diag(D->getLocation(), diag::err_member_name_of_class)
3661 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003662 break;
3663 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003664 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003665 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003666
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003667 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003668 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003669 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003670 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003671 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3672 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3673 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003674
3675 // See if a method overloads virtual methods in a base
3676 /// class without overriding any.
3677 if (!Record->isDependentType()) {
3678 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3679 MEnd = Record->method_end();
3680 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003681 if (!(*M)->isStatic())
3682 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003683 }
3684 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003685
Richard Smith9f569cc2011-10-01 02:31:28 +00003686 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3687 // function that is not a constructor declares that member function to be
3688 // const. [...] The class of which that function is a member shall be
3689 // a literal type.
3690 //
3691 // It's fine to diagnose constructors here too: such constructors cannot
3692 // produce a constant expression, so are ill-formed (no diagnostic required).
3693 //
3694 // If the class has virtual bases, any constexpr members will already have
3695 // been diagnosed by the checks performed on the member declaration, so
3696 // suppress this (less useful) diagnostic.
3697 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3698 !Record->isLiteral() && !Record->getNumVBases()) {
3699 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3700 MEnd = Record->method_end();
3701 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003702 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003703 switch (Record->getTemplateSpecializationKind()) {
3704 case TSK_ImplicitInstantiation:
3705 case TSK_ExplicitInstantiationDeclaration:
3706 case TSK_ExplicitInstantiationDefinition:
3707 // If a template instantiates to a non-literal type, but its members
3708 // instantiate to constexpr functions, the template is technically
3709 // ill-formed, but we allow it for sanity. Such members are treated as
3710 // non-constexpr.
3711 (*M)->setConstexpr(false);
3712 continue;
3713
3714 case TSK_Undeclared:
3715 case TSK_ExplicitSpecialization:
3716 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3717 PDiag(diag::err_constexpr_method_non_literal));
3718 break;
3719 }
3720
3721 // Only produce one error per class.
3722 break;
3723 }
3724 }
3725 }
3726
Sebastian Redlf677ea32011-02-05 19:23:19 +00003727 // Declare inherited constructors. We do this eagerly here because:
3728 // - The standard requires an eager diagnostic for conflicting inherited
3729 // constructors from different classes.
3730 // - The lazy declaration of the other implicit constructors is so as to not
3731 // waste space and performance on classes that are not meant to be
3732 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3733 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003734 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003735
Sean Hunteb88ae52011-05-23 21:07:59 +00003736 if (!Record->isDependentType())
3737 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003738}
3739
3740void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003741 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3742 ME = Record->method_end();
3743 MI != ME; ++MI) {
3744 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3745 switch (getSpecialMember(*MI)) {
3746 case CXXDefaultConstructor:
3747 CheckExplicitlyDefaultedDefaultConstructor(
3748 cast<CXXConstructorDecl>(*MI));
3749 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003750
Sean Huntcb45a0f2011-05-12 22:46:25 +00003751 case CXXDestructor:
3752 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3753 break;
3754
3755 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003756 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3757 break;
3758
Sean Huntcb45a0f2011-05-12 22:46:25 +00003759 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003760 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003761 break;
3762
Sean Hunt82713172011-05-25 23:16:36 +00003763 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003764 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003765 break;
3766
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003767 case CXXMoveAssignment:
3768 CheckExplicitlyDefaultedMoveAssignment(*MI);
3769 break;
3770
3771 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003772 llvm_unreachable("non-special member explicitly defaulted!");
3773 }
Sean Hunt001cad92011-05-10 00:49:42 +00003774 }
3775 }
3776
Sean Hunt001cad92011-05-10 00:49:42 +00003777}
3778
3779void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3780 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3781
3782 // Whether this was the first-declared instance of the constructor.
3783 // This affects whether we implicitly add an exception spec (and, eventually,
3784 // constexpr). It is also ill-formed to explicitly default a constructor such
3785 // that it would be deleted. (C++0x [decl.fct.def.default])
3786 bool First = CD == CD->getCanonicalDecl();
3787
Sean Hunt49634cf2011-05-13 06:10:58 +00003788 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003789 if (CD->getNumParams() != 0) {
3790 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3791 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003792 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003793 }
3794
3795 ImplicitExceptionSpecification Spec
3796 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3797 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003798 if (EPI.ExceptionSpecType == EST_Delayed) {
3799 // Exception specification depends on some deferred part of the class. We'll
3800 // try again when the class's definition has been fully processed.
3801 return;
3802 }
Sean Hunt001cad92011-05-10 00:49:42 +00003803 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3804 *ExceptionType = Context.getFunctionType(
3805 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3806
Richard Smith61802452011-12-22 02:22:31 +00003807 // C++11 [dcl.fct.def.default]p2:
3808 // An explicitly-defaulted function may be declared constexpr only if it
3809 // would have been implicitly declared as constexpr,
3810 if (CD->isConstexpr()) {
3811 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3812 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3813 << CXXDefaultConstructor;
3814 HadError = true;
3815 }
3816 }
3817 // and may have an explicit exception-specification only if it is compatible
3818 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003819 if (CtorType->hasExceptionSpec()) {
3820 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003821 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003822 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003823 PDiag(),
3824 ExceptionType, SourceLocation(),
3825 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003826 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003827 }
Richard Smith61802452011-12-22 02:22:31 +00003828 }
3829
3830 // If a function is explicitly defaulted on its first declaration,
3831 if (First) {
3832 // -- it is implicitly considered to be constexpr if the implicit
3833 // definition would be,
3834 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3835
3836 // -- it is implicitly considered to have the same
3837 // exception-specification as if it had been implicitly declared
3838 //
3839 // FIXME: a compatible, but different, explicit exception specification
3840 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003841 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003842 }
Sean Huntca46d132011-05-12 03:51:48 +00003843
Sean Hunt49634cf2011-05-13 06:10:58 +00003844 if (HadError) {
3845 CD->setInvalidDecl();
3846 return;
3847 }
3848
Sean Hunte16da072011-10-10 06:18:57 +00003849 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003850 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003851 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003852 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003853 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003854 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003855 CD->setInvalidDecl();
3856 }
3857 }
3858}
3859
3860void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3861 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3862
3863 // Whether this was the first-declared instance of the constructor.
3864 bool First = CD == CD->getCanonicalDecl();
3865
3866 bool HadError = false;
3867 if (CD->getNumParams() != 1) {
3868 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3869 << CD->getSourceRange();
3870 HadError = true;
3871 }
3872
3873 ImplicitExceptionSpecification Spec(Context);
3874 bool Const;
3875 llvm::tie(Spec, Const) =
3876 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3877
3878 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3879 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3880 *ExceptionType = Context.getFunctionType(
3881 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3882
3883 // Check for parameter type matching.
3884 // This is a copy ctor so we know it's a cv-qualified reference to T.
3885 QualType ArgType = CtorType->getArgType(0);
3886 if (ArgType->getPointeeType().isVolatileQualified()) {
3887 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3888 HadError = true;
3889 }
3890 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3891 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3892 HadError = true;
3893 }
3894
Richard Smith61802452011-12-22 02:22:31 +00003895 // C++11 [dcl.fct.def.default]p2:
3896 // An explicitly-defaulted function may be declared constexpr only if it
3897 // would have been implicitly declared as constexpr,
3898 if (CD->isConstexpr()) {
3899 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3900 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3901 << CXXCopyConstructor;
3902 HadError = true;
3903 }
3904 }
3905 // and may have an explicit exception-specification only if it is compatible
3906 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003907 if (CtorType->hasExceptionSpec()) {
3908 if (CheckEquivalentExceptionSpec(
3909 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003910 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003911 PDiag(),
3912 ExceptionType, SourceLocation(),
3913 CtorType, CD->getLocation())) {
3914 HadError = true;
3915 }
Richard Smith61802452011-12-22 02:22:31 +00003916 }
3917
3918 // If a function is explicitly defaulted on its first declaration,
3919 if (First) {
3920 // -- it is implicitly considered to be constexpr if the implicit
3921 // definition would be,
3922 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3923
3924 // -- it is implicitly considered to have the same
3925 // exception-specification as if it had been implicitly declared, and
3926 //
3927 // FIXME: a compatible, but different, explicit exception specification
3928 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003929 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003930
3931 // -- [...] it shall have the same parameter type as if it had been
3932 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003933 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3934 }
3935
3936 if (HadError) {
3937 CD->setInvalidDecl();
3938 return;
3939 }
3940
Sean Huntc32d6842011-10-11 04:55:36 +00003941 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003942 if (First) {
3943 CD->setDeletedAsWritten();
3944 } else {
3945 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003946 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003947 CD->setInvalidDecl();
3948 }
Sean Huntca46d132011-05-12 03:51:48 +00003949 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003950}
Sean Hunt001cad92011-05-10 00:49:42 +00003951
Sean Hunt2b188082011-05-14 05:23:28 +00003952void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3953 assert(MD->isExplicitlyDefaulted());
3954
3955 // Whether this was the first-declared instance of the operator
3956 bool First = MD == MD->getCanonicalDecl();
3957
3958 bool HadError = false;
3959 if (MD->getNumParams() != 1) {
3960 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3961 << MD->getSourceRange();
3962 HadError = true;
3963 }
3964
3965 QualType ReturnType =
3966 MD->getType()->getAs<FunctionType>()->getResultType();
3967 if (!ReturnType->isLValueReferenceType() ||
3968 !Context.hasSameType(
3969 Context.getCanonicalType(ReturnType->getPointeeType()),
3970 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3971 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3972 HadError = true;
3973 }
3974
3975 ImplicitExceptionSpecification Spec(Context);
3976 bool Const;
3977 llvm::tie(Spec, Const) =
3978 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3979
3980 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3981 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3982 *ExceptionType = Context.getFunctionType(
3983 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3984
Sean Hunt2b188082011-05-14 05:23:28 +00003985 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003986 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003987 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003988 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003989 } else {
3990 if (ArgType->getPointeeType().isVolatileQualified()) {
3991 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3992 HadError = true;
3993 }
3994 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3995 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3996 HadError = true;
3997 }
Sean Hunt2b188082011-05-14 05:23:28 +00003998 }
Sean Huntbe631222011-05-17 20:44:43 +00003999
Sean Hunt2b188082011-05-14 05:23:28 +00004000 if (OperType->getTypeQuals()) {
4001 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4002 HadError = true;
4003 }
4004
4005 if (OperType->hasExceptionSpec()) {
4006 if (CheckEquivalentExceptionSpec(
4007 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004008 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004009 PDiag(),
4010 ExceptionType, SourceLocation(),
4011 OperType, MD->getLocation())) {
4012 HadError = true;
4013 }
Richard Smith61802452011-12-22 02:22:31 +00004014 }
4015 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004016 // We set the declaration to have the computed exception spec here.
4017 // We duplicate the one parameter type.
4018 EPI.RefQualifier = OperType->getRefQualifier();
4019 EPI.ExtInfo = OperType->getExtInfo();
4020 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4021 }
4022
4023 if (HadError) {
4024 MD->setInvalidDecl();
4025 return;
4026 }
4027
4028 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4029 if (First) {
4030 MD->setDeletedAsWritten();
4031 } else {
4032 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004033 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004034 MD->setInvalidDecl();
4035 }
4036 }
4037}
4038
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004039void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4040 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4041
4042 // Whether this was the first-declared instance of the constructor.
4043 bool First = CD == CD->getCanonicalDecl();
4044
4045 bool HadError = false;
4046 if (CD->getNumParams() != 1) {
4047 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4048 << CD->getSourceRange();
4049 HadError = true;
4050 }
4051
4052 ImplicitExceptionSpecification Spec(
4053 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4054
4055 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4056 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4057 *ExceptionType = Context.getFunctionType(
4058 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4059
4060 // Check for parameter type matching.
4061 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4062 QualType ArgType = CtorType->getArgType(0);
4063 if (ArgType->getPointeeType().isVolatileQualified()) {
4064 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4065 HadError = true;
4066 }
4067 if (ArgType->getPointeeType().isConstQualified()) {
4068 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4069 HadError = true;
4070 }
4071
Richard Smith61802452011-12-22 02:22:31 +00004072 // C++11 [dcl.fct.def.default]p2:
4073 // An explicitly-defaulted function may be declared constexpr only if it
4074 // would have been implicitly declared as constexpr,
4075 if (CD->isConstexpr()) {
4076 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4077 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4078 << CXXMoveConstructor;
4079 HadError = true;
4080 }
4081 }
4082 // and may have an explicit exception-specification only if it is compatible
4083 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004084 if (CtorType->hasExceptionSpec()) {
4085 if (CheckEquivalentExceptionSpec(
4086 PDiag(diag::err_incorrect_defaulted_exception_spec)
4087 << CXXMoveConstructor,
4088 PDiag(),
4089 ExceptionType, SourceLocation(),
4090 CtorType, CD->getLocation())) {
4091 HadError = true;
4092 }
Richard Smith61802452011-12-22 02:22:31 +00004093 }
4094
4095 // If a function is explicitly defaulted on its first declaration,
4096 if (First) {
4097 // -- it is implicitly considered to be constexpr if the implicit
4098 // definition would be,
4099 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4100
4101 // -- it is implicitly considered to have the same
4102 // exception-specification as if it had been implicitly declared, and
4103 //
4104 // FIXME: a compatible, but different, explicit exception specification
4105 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004106 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004107
4108 // -- [...] it shall have the same parameter type as if it had been
4109 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004110 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4111 }
4112
4113 if (HadError) {
4114 CD->setInvalidDecl();
4115 return;
4116 }
4117
Sean Hunt769bb2d2011-10-11 06:43:29 +00004118 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004119 if (First) {
4120 CD->setDeletedAsWritten();
4121 } else {
4122 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4123 << CXXMoveConstructor;
4124 CD->setInvalidDecl();
4125 }
4126 }
4127}
4128
4129void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4130 assert(MD->isExplicitlyDefaulted());
4131
4132 // Whether this was the first-declared instance of the operator
4133 bool First = MD == MD->getCanonicalDecl();
4134
4135 bool HadError = false;
4136 if (MD->getNumParams() != 1) {
4137 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4138 << MD->getSourceRange();
4139 HadError = true;
4140 }
4141
4142 QualType ReturnType =
4143 MD->getType()->getAs<FunctionType>()->getResultType();
4144 if (!ReturnType->isLValueReferenceType() ||
4145 !Context.hasSameType(
4146 Context.getCanonicalType(ReturnType->getPointeeType()),
4147 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4148 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4149 HadError = true;
4150 }
4151
4152 ImplicitExceptionSpecification Spec(
4153 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4154
4155 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4156 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4157 *ExceptionType = Context.getFunctionType(
4158 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4159
4160 QualType ArgType = OperType->getArgType(0);
4161 if (!ArgType->isRValueReferenceType()) {
4162 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4163 HadError = true;
4164 } else {
4165 if (ArgType->getPointeeType().isVolatileQualified()) {
4166 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4167 HadError = true;
4168 }
4169 if (ArgType->getPointeeType().isConstQualified()) {
4170 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4171 HadError = true;
4172 }
4173 }
4174
4175 if (OperType->getTypeQuals()) {
4176 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4177 HadError = true;
4178 }
4179
4180 if (OperType->hasExceptionSpec()) {
4181 if (CheckEquivalentExceptionSpec(
4182 PDiag(diag::err_incorrect_defaulted_exception_spec)
4183 << CXXMoveAssignment,
4184 PDiag(),
4185 ExceptionType, SourceLocation(),
4186 OperType, MD->getLocation())) {
4187 HadError = true;
4188 }
Richard Smith61802452011-12-22 02:22:31 +00004189 }
4190 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004191 // We set the declaration to have the computed exception spec here.
4192 // We duplicate the one parameter type.
4193 EPI.RefQualifier = OperType->getRefQualifier();
4194 EPI.ExtInfo = OperType->getExtInfo();
4195 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4196 }
4197
4198 if (HadError) {
4199 MD->setInvalidDecl();
4200 return;
4201 }
4202
4203 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4204 if (First) {
4205 MD->setDeletedAsWritten();
4206 } else {
4207 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4208 << CXXMoveAssignment;
4209 MD->setInvalidDecl();
4210 }
4211 }
4212}
4213
Sean Huntcb45a0f2011-05-12 22:46:25 +00004214void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4215 assert(DD->isExplicitlyDefaulted());
4216
4217 // Whether this was the first-declared instance of the destructor.
4218 bool First = DD == DD->getCanonicalDecl();
4219
4220 ImplicitExceptionSpecification Spec
4221 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4222 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4223 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4224 *ExceptionType = Context.getFunctionType(
4225 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4226
4227 if (DtorType->hasExceptionSpec()) {
4228 if (CheckEquivalentExceptionSpec(
4229 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004230 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004231 PDiag(),
4232 ExceptionType, SourceLocation(),
4233 DtorType, DD->getLocation())) {
4234 DD->setInvalidDecl();
4235 return;
4236 }
Richard Smith61802452011-12-22 02:22:31 +00004237 }
4238 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004239 // We set the declaration to have the computed exception spec here.
4240 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004241 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004242 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4243 }
4244
4245 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004246 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004247 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004248 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004249 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004250 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004251 DD->setInvalidDecl();
4252 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004253 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004254}
4255
Sean Hunte16da072011-10-10 06:18:57 +00004256/// This function implements the following C++0x paragraphs:
4257/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004258/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004259bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4260 assert(!MD->isInvalidDecl());
4261 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004262 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004263 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004264 return false;
4265
Sean Hunte16da072011-10-10 06:18:57 +00004266 bool IsUnion = RD->isUnion();
4267 bool IsConstructor = false;
4268 bool IsAssignment = false;
4269 bool IsMove = false;
4270
4271 bool ConstArg = false;
4272
4273 switch (CSM) {
4274 case CXXDefaultConstructor:
4275 IsConstructor = true;
4276 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004277 case CXXCopyConstructor:
4278 IsConstructor = true;
4279 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4280 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004281 case CXXMoveConstructor:
4282 IsConstructor = true;
4283 IsMove = true;
4284 break;
Sean Hunte16da072011-10-10 06:18:57 +00004285 default:
4286 llvm_unreachable("function only currently implemented for default ctors");
4287 }
4288
4289 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004290
Sean Huntc32d6842011-10-11 04:55:36 +00004291 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004292 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004293
Sean Huntcdee3fe2011-05-11 22:34:38 +00004294 bool AllConst = true;
4295
Sean Huntcdee3fe2011-05-11 22:34:38 +00004296 // We do this because we should never actually use an anonymous
4297 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004298 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004299 return false;
4300
4301 // FIXME: We should put some diagnostic logic right into this function.
4302
Sean Huntcdee3fe2011-05-11 22:34:38 +00004303 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4304 BE = RD->bases_end();
4305 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004306 // We'll handle this one later
4307 if (BI->isVirtual())
4308 continue;
4309
Sean Huntcdee3fe2011-05-11 22:34:38 +00004310 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4311 assert(BaseDecl && "base isn't a CXXRecordDecl");
4312
Sean Hunte16da072011-10-10 06:18:57 +00004313 // Unless we have an assignment operator, the base's destructor must
4314 // be accessible and not deleted.
4315 if (!IsAssignment) {
4316 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4317 if (BaseDtor->isDeleted())
4318 return true;
4319 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4320 AR_accessible)
4321 return true;
4322 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004323
Sean Hunte16da072011-10-10 06:18:57 +00004324 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004325 // unique, accessible, non-deleted function. If we are doing
4326 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004327 if (CSM != CXXDestructor) {
4328 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004329 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004330 false);
4331 if (!SMOR->hasSuccess())
4332 return true;
4333 CXXMethodDecl *BaseMember = SMOR->getMethod();
4334 if (IsConstructor) {
4335 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4336 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4337 PDiag()) != AR_accessible)
4338 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004339
4340 // For a move operation, the corresponding operation must actually
4341 // be a move operation (and not a copy selected by overload
4342 // resolution) unless we are working on a trivially copyable class.
4343 if (IsMove && !BaseCtor->isMoveConstructor() &&
4344 !BaseDecl->isTriviallyCopyable())
4345 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004346 }
4347 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004348 }
4349
4350 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4351 BE = RD->vbases_end();
4352 BI != BE; ++BI) {
4353 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4354 assert(BaseDecl && "base isn't a CXXRecordDecl");
4355
Sean Hunte16da072011-10-10 06:18:57 +00004356 // Unless we have an assignment operator, the base's destructor must
4357 // be accessible and not deleted.
4358 if (!IsAssignment) {
4359 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4360 if (BaseDtor->isDeleted())
4361 return true;
4362 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4363 AR_accessible)
4364 return true;
4365 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004366
Sean Hunte16da072011-10-10 06:18:57 +00004367 // Finding the corresponding member in the base should lead to a
4368 // unique, accessible, non-deleted function.
4369 if (CSM != CXXDestructor) {
4370 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004371 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004372 false);
4373 if (!SMOR->hasSuccess())
4374 return true;
4375 CXXMethodDecl *BaseMember = SMOR->getMethod();
4376 if (IsConstructor) {
4377 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4378 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4379 PDiag()) != AR_accessible)
4380 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004381
4382 // For a move operation, the corresponding operation must actually
4383 // be a move operation (and not a copy selected by overload
4384 // resolution) unless we are working on a trivially copyable class.
4385 if (IsMove && !BaseCtor->isMoveConstructor() &&
4386 !BaseDecl->isTriviallyCopyable())
4387 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004388 }
4389 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004390 }
4391
4392 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4393 FE = RD->field_end();
4394 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004395 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004396 continue;
4397
Sean Huntcdee3fe2011-05-11 22:34:38 +00004398 QualType FieldType = Context.getBaseElementType(FI->getType());
4399 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004400
Sean Hunte16da072011-10-10 06:18:57 +00004401 // For a default constructor, all references must be initialized in-class
4402 // and, if a union, it must have a non-const member.
4403 if (CSM == CXXDefaultConstructor) {
4404 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4405 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004406
Sean Hunte16da072011-10-10 06:18:57 +00004407 if (IsUnion && !FieldType.isConstQualified())
4408 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004409 // For a copy constructor, data members must not be of rvalue reference
4410 // type.
4411 } else if (CSM == CXXCopyConstructor) {
4412 if (FieldType->isRValueReferenceType())
4413 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004414 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004415
4416 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004417 // For a default constructor, a const member must have a user-provided
4418 // default constructor or else be explicitly initialized.
4419 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004420 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004421 !FieldRecord->hasUserProvidedDefaultConstructor())
4422 return true;
4423
Sean Huntc32d6842011-10-11 04:55:36 +00004424 // Some additional restrictions exist on the variant members.
4425 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004426 FieldRecord->isAnonymousStructOrUnion()) {
4427 // We're okay to reuse AllConst here since we only care about the
4428 // value otherwise if we're in a union.
4429 AllConst = true;
4430
4431 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4432 UE = FieldRecord->field_end();
4433 UI != UE; ++UI) {
4434 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4435 CXXRecordDecl *UnionFieldRecord =
4436 UnionFieldType->getAsCXXRecordDecl();
4437
4438 if (!UnionFieldType.isConstQualified())
4439 AllConst = false;
4440
Sean Huntc32d6842011-10-11 04:55:36 +00004441 if (UnionFieldRecord) {
4442 // FIXME: Checking for accessibility and validity of this
4443 // destructor is technically going beyond the
4444 // standard, but this is believed to be a defect.
4445 if (!IsAssignment) {
4446 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4447 if (FieldDtor->isDeleted())
4448 return true;
4449 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4450 AR_accessible)
4451 return true;
4452 if (!FieldDtor->isTrivial())
4453 return true;
4454 }
4455
4456 if (CSM != CXXDestructor) {
4457 SpecialMemberOverloadResult *SMOR =
4458 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004459 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004460 // FIXME: Checking for accessibility and validity of this
4461 // corresponding member is technically going beyond the
4462 // standard, but this is believed to be a defect.
4463 if (!SMOR->hasSuccess())
4464 return true;
4465
4466 CXXMethodDecl *FieldMember = SMOR->getMethod();
4467 // A member of a union must have a trivial corresponding
4468 // constructor.
4469 if (!FieldMember->isTrivial())
4470 return true;
4471
4472 if (IsConstructor) {
4473 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4474 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4475 PDiag()) != AR_accessible)
4476 return true;
4477 }
4478 }
4479 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004480 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004481
Sean Huntc32d6842011-10-11 04:55:36 +00004482 // At least one member in each anonymous union must be non-const
4483 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004484 return true;
4485
4486 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004487 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004488 continue;
4489 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004490
Sean Huntc32d6842011-10-11 04:55:36 +00004491 // Unless we're doing assignment, the field's destructor must be
4492 // accessible and not deleted.
4493 if (!IsAssignment) {
4494 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4495 if (FieldDtor->isDeleted())
4496 return true;
4497 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4498 AR_accessible)
4499 return true;
4500 }
4501
Sean Hunte16da072011-10-10 06:18:57 +00004502 // Check that the corresponding member of the field is accessible,
4503 // unique, and non-deleted. We don't do this if it has an explicit
4504 // initialization when default-constructing.
4505 if (CSM != CXXDestructor &&
4506 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4507 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004508 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004509 false);
4510 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004511 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004512
4513 CXXMethodDecl *FieldMember = SMOR->getMethod();
4514 if (IsConstructor) {
4515 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4516 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4517 PDiag()) != AR_accessible)
4518 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004519
4520 // For a move operation, the corresponding operation must actually
4521 // be a move operation (and not a copy selected by overload
4522 // resolution) unless we are working on a trivially copyable class.
4523 if (IsMove && !FieldCtor->isMoveConstructor() &&
4524 !FieldRecord->isTriviallyCopyable())
4525 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004526 }
4527
4528 // We need the corresponding member of a union to be trivial so that
4529 // we can safely copy them all simultaneously.
4530 // FIXME: Note that performing the check here (where we rely on the lack
4531 // of an in-class initializer) is technically ill-formed. However, this
4532 // seems most obviously to be a bug in the standard.
4533 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004534 return true;
4535 }
Sean Hunte16da072011-10-10 06:18:57 +00004536 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4537 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4538 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004539 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004540 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004541 }
4542
Sean Hunte16da072011-10-10 06:18:57 +00004543 // We can't have all const members in a union when default-constructing,
4544 // or else they're all nonsensical garbage values that can't be changed.
4545 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004546 return true;
4547
4548 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004549}
4550
Sean Hunt7f410192011-05-14 05:23:24 +00004551bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4552 CXXRecordDecl *RD = MD->getParent();
4553 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004554 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004555 return false;
4556
Sean Hunt71a682f2011-05-18 03:41:58 +00004557 SourceLocation Loc = MD->getLocation();
4558
Sean Hunt7f410192011-05-14 05:23:24 +00004559 // Do access control from the constructor
4560 ContextRAII MethodContext(*this, MD);
4561
4562 bool Union = RD->isUnion();
4563
Sean Hunt661c67a2011-06-21 23:42:56 +00004564 unsigned ArgQuals =
4565 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4566 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004567
4568 // We do this because we should never actually use an anonymous
4569 // union's constructor.
4570 if (Union && RD->isAnonymousStructOrUnion())
4571 return false;
4572
Sean Hunt7f410192011-05-14 05:23:24 +00004573 // FIXME: We should put some diagnostic logic right into this function.
4574
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004575 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004576 // A defaulted [copy] assignment operator for class X is defined as deleted
4577 // if X has:
4578
4579 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4580 BE = RD->bases_end();
4581 BI != BE; ++BI) {
4582 // We'll handle this one later
4583 if (BI->isVirtual())
4584 continue;
4585
4586 QualType BaseType = BI->getType();
4587 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4588 assert(BaseDecl && "base isn't a CXXRecordDecl");
4589
4590 // -- a [direct base class] B that cannot be [copied] because overload
4591 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004592 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004593 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004594 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4595 0);
4596 if (!CopyOper || CopyOper->isDeleted())
4597 return true;
4598 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004599 return true;
4600 }
4601
4602 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4603 BE = RD->vbases_end();
4604 BI != BE; ++BI) {
4605 QualType BaseType = BI->getType();
4606 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4607 assert(BaseDecl && "base isn't a CXXRecordDecl");
4608
Sean Hunt7f410192011-05-14 05:23:24 +00004609 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004610 // resolution, as applied to B's [copy] assignment operator, results in
4611 // an ambiguity or a function that is deleted or inaccessible from the
4612 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004613 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4614 0);
4615 if (!CopyOper || CopyOper->isDeleted())
4616 return true;
4617 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004618 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004619 }
4620
4621 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4622 FE = RD->field_end();
4623 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004624 if (FI->isUnnamedBitfield())
4625 continue;
4626
Sean Hunt7f410192011-05-14 05:23:24 +00004627 QualType FieldType = Context.getBaseElementType(FI->getType());
4628
4629 // -- a non-static data member of reference type
4630 if (FieldType->isReferenceType())
4631 return true;
4632
4633 // -- a non-static data member of const non-class type (or array thereof)
4634 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4635 return true;
4636
4637 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4638
4639 if (FieldRecord) {
4640 // This is an anonymous union
4641 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4642 // Anonymous unions inside unions do not variant members create
4643 if (!Union) {
4644 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4645 UE = FieldRecord->field_end();
4646 UI != UE; ++UI) {
4647 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4648 CXXRecordDecl *UnionFieldRecord =
4649 UnionFieldType->getAsCXXRecordDecl();
4650
4651 // -- a variant member with a non-trivial [copy] assignment operator
4652 // and X is a union-like class
4653 if (UnionFieldRecord &&
4654 !UnionFieldRecord->hasTrivialCopyAssignment())
4655 return true;
4656 }
4657 }
4658
4659 // Don't try to initalize an anonymous union
4660 continue;
4661 // -- a variant member with a non-trivial [copy] assignment operator
4662 // and X is a union-like class
4663 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4664 return true;
4665 }
Sean Hunt7f410192011-05-14 05:23:24 +00004666
Sean Hunt661c67a2011-06-21 23:42:56 +00004667 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4668 false, 0);
4669 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004670 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004671 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004672 return true;
4673 }
4674 }
4675
4676 return false;
4677}
4678
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004679bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4680 CXXRecordDecl *RD = MD->getParent();
4681 assert(!RD->isDependentType() && "do deletion after instantiation");
4682 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4683 return false;
4684
4685 SourceLocation Loc = MD->getLocation();
4686
4687 // Do access control from the constructor
4688 ContextRAII MethodContext(*this, MD);
4689
4690 bool Union = RD->isUnion();
4691
4692 // We do this because we should never actually use an anonymous
4693 // union's constructor.
4694 if (Union && RD->isAnonymousStructOrUnion())
4695 return false;
4696
4697 // C++0x [class.copy]/20
4698 // A defaulted [move] assignment operator for class X is defined as deleted
4699 // if X has:
4700
4701 // -- for the move constructor, [...] any direct or indirect virtual base
4702 // class.
4703 if (RD->getNumVBases() != 0)
4704 return true;
4705
4706 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4707 BE = RD->bases_end();
4708 BI != BE; ++BI) {
4709
4710 QualType BaseType = BI->getType();
4711 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4712 assert(BaseDecl && "base isn't a CXXRecordDecl");
4713
4714 // -- a [direct base class] B that cannot be [moved] because overload
4715 // resolution, as applied to B's [move] assignment operator, results in
4716 // an ambiguity or a function that is deleted or inaccessible from the
4717 // assignment operator
4718 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4719 if (!MoveOper || MoveOper->isDeleted())
4720 return true;
4721 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4722 return true;
4723
4724 // -- for the move assignment operator, a [direct base class] with a type
4725 // that does not have a move assignment operator and is not trivially
4726 // copyable.
4727 if (!MoveOper->isMoveAssignmentOperator() &&
4728 !BaseDecl->isTriviallyCopyable())
4729 return true;
4730 }
4731
4732 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4733 FE = RD->field_end();
4734 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004735 if (FI->isUnnamedBitfield())
4736 continue;
4737
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004738 QualType FieldType = Context.getBaseElementType(FI->getType());
4739
4740 // -- a non-static data member of reference type
4741 if (FieldType->isReferenceType())
4742 return true;
4743
4744 // -- a non-static data member of const non-class type (or array thereof)
4745 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4746 return true;
4747
4748 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4749
4750 if (FieldRecord) {
4751 // This is an anonymous union
4752 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4753 // Anonymous unions inside unions do not variant members create
4754 if (!Union) {
4755 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4756 UE = FieldRecord->field_end();
4757 UI != UE; ++UI) {
4758 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4759 CXXRecordDecl *UnionFieldRecord =
4760 UnionFieldType->getAsCXXRecordDecl();
4761
4762 // -- a variant member with a non-trivial [move] assignment operator
4763 // and X is a union-like class
4764 if (UnionFieldRecord &&
4765 !UnionFieldRecord->hasTrivialMoveAssignment())
4766 return true;
4767 }
4768 }
4769
4770 // Don't try to initalize an anonymous union
4771 continue;
4772 // -- a variant member with a non-trivial [move] assignment operator
4773 // and X is a union-like class
4774 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4775 return true;
4776 }
4777
4778 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4779 if (!MoveOper || MoveOper->isDeleted())
4780 return true;
4781 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4782 return true;
4783
4784 // -- for the move assignment operator, a [non-static data member] with a
4785 // type that does not have a move assignment operator and is not
4786 // trivially copyable.
4787 if (!MoveOper->isMoveAssignmentOperator() &&
4788 !FieldRecord->isTriviallyCopyable())
4789 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004790 }
Sean Hunt7f410192011-05-14 05:23:24 +00004791 }
4792
4793 return false;
4794}
4795
Sean Huntcb45a0f2011-05-12 22:46:25 +00004796bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4797 CXXRecordDecl *RD = DD->getParent();
4798 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004799 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004800 return false;
4801
Sean Hunt71a682f2011-05-18 03:41:58 +00004802 SourceLocation Loc = DD->getLocation();
4803
Sean Huntcb45a0f2011-05-12 22:46:25 +00004804 // Do access control from the destructor
4805 ContextRAII CtorContext(*this, DD);
4806
4807 bool Union = RD->isUnion();
4808
Sean Hunt49634cf2011-05-13 06:10:58 +00004809 // We do this because we should never actually use an anonymous
4810 // union's destructor.
4811 if (Union && RD->isAnonymousStructOrUnion())
4812 return false;
4813
Sean Huntcb45a0f2011-05-12 22:46:25 +00004814 // C++0x [class.dtor]p5
4815 // A defaulted destructor for a class X is defined as deleted if:
4816 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4817 BE = RD->bases_end();
4818 BI != BE; ++BI) {
4819 // We'll handle this one later
4820 if (BI->isVirtual())
4821 continue;
4822
4823 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4824 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4825 assert(BaseDtor && "base has no destructor");
4826
4827 // -- any direct or virtual base class has a deleted destructor or
4828 // a destructor that is inaccessible from the defaulted destructor
4829 if (BaseDtor->isDeleted())
4830 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004831 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004832 AR_accessible)
4833 return true;
4834 }
4835
4836 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4837 BE = RD->vbases_end();
4838 BI != BE; ++BI) {
4839 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4840 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4841 assert(BaseDtor && "base has no destructor");
4842
4843 // -- any direct or virtual base class has a deleted destructor or
4844 // a destructor that is inaccessible from the defaulted destructor
4845 if (BaseDtor->isDeleted())
4846 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004847 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004848 AR_accessible)
4849 return true;
4850 }
4851
4852 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4853 FE = RD->field_end();
4854 FI != FE; ++FI) {
4855 QualType FieldType = Context.getBaseElementType(FI->getType());
4856 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4857 if (FieldRecord) {
4858 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4859 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4860 UE = FieldRecord->field_end();
4861 UI != UE; ++UI) {
4862 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4863 CXXRecordDecl *UnionFieldRecord =
4864 UnionFieldType->getAsCXXRecordDecl();
4865
4866 // -- X is a union-like class that has a variant member with a non-
4867 // trivial destructor.
4868 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4869 return true;
4870 }
4871 // Technically we are supposed to do this next check unconditionally.
4872 // But that makes absolutely no sense.
4873 } else {
4874 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4875
4876 // -- any of the non-static data members has class type M (or array
4877 // thereof) and M has a deleted destructor or a destructor that is
4878 // inaccessible from the defaulted destructor
4879 if (FieldDtor->isDeleted())
4880 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004881 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004882 AR_accessible)
4883 return true;
4884
4885 // -- X is a union-like class that has a variant member with a non-
4886 // trivial destructor.
4887 if (Union && !FieldDtor->isTrivial())
4888 return true;
4889 }
4890 }
4891 }
4892
4893 if (DD->isVirtual()) {
4894 FunctionDecl *OperatorDelete = 0;
4895 DeclarationName Name =
4896 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004897 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004898 false))
4899 return true;
4900 }
4901
4902
4903 return false;
4904}
4905
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004906/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004907namespace {
4908 struct FindHiddenVirtualMethodData {
4909 Sema *S;
4910 CXXMethodDecl *Method;
4911 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004912 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004913 };
4914}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004915
4916/// \brief Member lookup function that determines whether a given C++
4917/// method overloads virtual methods in a base class without overriding any,
4918/// to be used with CXXRecordDecl::lookupInBases().
4919static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4920 CXXBasePath &Path,
4921 void *UserData) {
4922 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4923
4924 FindHiddenVirtualMethodData &Data
4925 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4926
4927 DeclarationName Name = Data.Method->getDeclName();
4928 assert(Name.getNameKind() == DeclarationName::Identifier);
4929
4930 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004931 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004932 for (Path.Decls = BaseRecord->lookup(Name);
4933 Path.Decls.first != Path.Decls.second;
4934 ++Path.Decls.first) {
4935 NamedDecl *D = *Path.Decls.first;
4936 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004937 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004938 foundSameNameMethod = true;
4939 // Interested only in hidden virtual methods.
4940 if (!MD->isVirtual())
4941 continue;
4942 // If the method we are checking overrides a method from its base
4943 // don't warn about the other overloaded methods.
4944 if (!Data.S->IsOverload(Data.Method, MD, false))
4945 return true;
4946 // Collect the overload only if its hidden.
4947 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4948 overloadedMethods.push_back(MD);
4949 }
4950 }
4951
4952 if (foundSameNameMethod)
4953 Data.OverloadedMethods.append(overloadedMethods.begin(),
4954 overloadedMethods.end());
4955 return foundSameNameMethod;
4956}
4957
4958/// \brief See if a method overloads virtual methods in a base class without
4959/// overriding any.
4960void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4961 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004962 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004963 return;
4964 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4965 return;
4966
4967 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4968 /*bool RecordPaths=*/false,
4969 /*bool DetectVirtual=*/false);
4970 FindHiddenVirtualMethodData Data;
4971 Data.Method = MD;
4972 Data.S = this;
4973
4974 // Keep the base methods that were overriden or introduced in the subclass
4975 // by 'using' in a set. A base method not in this set is hidden.
4976 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4977 res.first != res.second; ++res.first) {
4978 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4979 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4980 E = MD->end_overridden_methods();
4981 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004982 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004983 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4984 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004985 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004986 }
4987
4988 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4989 !Data.OverloadedMethods.empty()) {
4990 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4991 << MD << (Data.OverloadedMethods.size() > 1);
4992
4993 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4994 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4995 Diag(overloadedMD->getLocation(),
4996 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4997 }
4998 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004999}
5000
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005001void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005002 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005003 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005004 SourceLocation RBrac,
5005 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005006 if (!TagDecl)
5007 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005008
Douglas Gregor42af25f2009-05-11 19:58:34 +00005009 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005010
David Blaikie77b6de02011-09-22 02:58:26 +00005011 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005012 // strict aliasing violation!
5013 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005014 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005015
Douglas Gregor23c94db2010-07-02 17:43:08 +00005016 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005017 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005018}
5019
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005020/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5021/// special functions, such as the default constructor, copy
5022/// constructor, or destructor, to the given C++ class (C++
5023/// [special]p1). This routine can only be executed just before the
5024/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005025void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005026 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005027 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005028
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005029 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005030 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005031
Richard Smithb701d3d2011-12-24 21:56:24 +00005032 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5033 ++ASTContext::NumImplicitMoveConstructors;
5034
Douglas Gregora376d102010-07-02 21:50:04 +00005035 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5036 ++ASTContext::NumImplicitCopyAssignmentOperators;
5037
5038 // If we have a dynamic class, then the copy assignment operator may be
5039 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5040 // it shows up in the right place in the vtable and that we diagnose
5041 // problems with the implicit exception specification.
5042 if (ClassDecl->isDynamicClass())
5043 DeclareImplicitCopyAssignment(ClassDecl);
5044 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005045
Richard Smithb701d3d2011-12-24 21:56:24 +00005046 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5047 ++ASTContext::NumImplicitMoveAssignmentOperators;
5048
5049 // Likewise for the move assignment operator.
5050 if (ClassDecl->isDynamicClass())
5051 DeclareImplicitMoveAssignment(ClassDecl);
5052 }
5053
Douglas Gregor4923aa22010-07-02 20:37:36 +00005054 if (!ClassDecl->hasUserDeclaredDestructor()) {
5055 ++ASTContext::NumImplicitDestructors;
5056
5057 // If we have a dynamic class, then the destructor may be virtual, so we
5058 // have to declare the destructor immediately. This ensures that, e.g., it
5059 // shows up in the right place in the vtable and that we diagnose problems
5060 // with the implicit exception specification.
5061 if (ClassDecl->isDynamicClass())
5062 DeclareImplicitDestructor(ClassDecl);
5063 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005064}
5065
Francois Pichet8387e2a2011-04-22 22:18:13 +00005066void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5067 if (!D)
5068 return;
5069
5070 int NumParamList = D->getNumTemplateParameterLists();
5071 for (int i = 0; i < NumParamList; i++) {
5072 TemplateParameterList* Params = D->getTemplateParameterList(i);
5073 for (TemplateParameterList::iterator Param = Params->begin(),
5074 ParamEnd = Params->end();
5075 Param != ParamEnd; ++Param) {
5076 NamedDecl *Named = cast<NamedDecl>(*Param);
5077 if (Named->getDeclName()) {
5078 S->AddDecl(Named);
5079 IdResolver.AddDecl(Named);
5080 }
5081 }
5082 }
5083}
5084
John McCalld226f652010-08-21 09:40:31 +00005085void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005086 if (!D)
5087 return;
5088
5089 TemplateParameterList *Params = 0;
5090 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5091 Params = Template->getTemplateParameters();
5092 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5093 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5094 Params = PartialSpec->getTemplateParameters();
5095 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005096 return;
5097
Douglas Gregor6569d682009-05-27 23:11:45 +00005098 for (TemplateParameterList::iterator Param = Params->begin(),
5099 ParamEnd = Params->end();
5100 Param != ParamEnd; ++Param) {
5101 NamedDecl *Named = cast<NamedDecl>(*Param);
5102 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005103 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005104 IdResolver.AddDecl(Named);
5105 }
5106 }
5107}
5108
John McCalld226f652010-08-21 09:40:31 +00005109void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005110 if (!RecordD) return;
5111 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005112 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005113 PushDeclContext(S, Record);
5114}
5115
John McCalld226f652010-08-21 09:40:31 +00005116void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005117 if (!RecordD) return;
5118 PopDeclContext();
5119}
5120
Douglas Gregor72b505b2008-12-16 21:30:33 +00005121/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5122/// parsing a top-level (non-nested) C++ class, and we are now
5123/// parsing those parts of the given Method declaration that could
5124/// not be parsed earlier (C++ [class.mem]p2), such as default
5125/// arguments. This action should enter the scope of the given
5126/// Method declaration as if we had just parsed the qualified method
5127/// name. However, it should not bring the parameters into scope;
5128/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005129void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005130}
5131
5132/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5133/// C++ method declaration. We're (re-)introducing the given
5134/// function parameter into scope for use in parsing later parts of
5135/// the method declaration. For example, we could see an
5136/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005137void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005138 if (!ParamD)
5139 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005140
John McCalld226f652010-08-21 09:40:31 +00005141 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005142
5143 // If this parameter has an unparsed default argument, clear it out
5144 // to make way for the parsed default argument.
5145 if (Param->hasUnparsedDefaultArg())
5146 Param->setDefaultArg(0);
5147
John McCalld226f652010-08-21 09:40:31 +00005148 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005149 if (Param->getDeclName())
5150 IdResolver.AddDecl(Param);
5151}
5152
5153/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5154/// processing the delayed method declaration for Method. The method
5155/// declaration is now considered finished. There may be a separate
5156/// ActOnStartOfFunctionDef action later (not necessarily
5157/// immediately!) for this method, if it was also defined inside the
5158/// class body.
John McCalld226f652010-08-21 09:40:31 +00005159void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005160 if (!MethodD)
5161 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005162
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005163 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005164
John McCalld226f652010-08-21 09:40:31 +00005165 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005166
5167 // Now that we have our default arguments, check the constructor
5168 // again. It could produce additional diagnostics or affect whether
5169 // the class has implicitly-declared destructors, among other
5170 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005171 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5172 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005173
5174 // Check the default arguments, which we may have added.
5175 if (!Method->isInvalidDecl())
5176 CheckCXXDefaultArguments(Method);
5177}
5178
Douglas Gregor42a552f2008-11-05 20:51:48 +00005179/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005180/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005181/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005182/// emit diagnostics and set the invalid bit to true. In any case, the type
5183/// will be updated to reflect a well-formed type for the constructor and
5184/// returned.
5185QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005186 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005187 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005188
5189 // C++ [class.ctor]p3:
5190 // A constructor shall not be virtual (10.3) or static (9.4). A
5191 // constructor can be invoked for a const, volatile or const
5192 // volatile object. A constructor shall not be declared const,
5193 // volatile, or const volatile (9.3.2).
5194 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005195 if (!D.isInvalidType())
5196 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5197 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5198 << SourceRange(D.getIdentifierLoc());
5199 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005200 }
John McCalld931b082010-08-26 03:08:43 +00005201 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005202 if (!D.isInvalidType())
5203 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5204 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5205 << SourceRange(D.getIdentifierLoc());
5206 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005207 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005208 }
Mike Stump1eb44332009-09-09 15:08:12 +00005209
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005210 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005211 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005212 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005213 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5214 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005215 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005216 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5217 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005218 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005219 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5220 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005221 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005222 }
Mike Stump1eb44332009-09-09 15:08:12 +00005223
Douglas Gregorc938c162011-01-26 05:01:58 +00005224 // C++0x [class.ctor]p4:
5225 // A constructor shall not be declared with a ref-qualifier.
5226 if (FTI.hasRefQualifier()) {
5227 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5228 << FTI.RefQualifierIsLValueRef
5229 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5230 D.setInvalidType();
5231 }
5232
Douglas Gregor42a552f2008-11-05 20:51:48 +00005233 // Rebuild the function type "R" without any type qualifiers (in
5234 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005235 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005236 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005237 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5238 return R;
5239
5240 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5241 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005242 EPI.RefQualifier = RQ_None;
5243
Chris Lattner65401802009-04-25 08:28:21 +00005244 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005245 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005246}
5247
Douglas Gregor72b505b2008-12-16 21:30:33 +00005248/// CheckConstructor - Checks a fully-formed constructor for
5249/// well-formedness, issuing any diagnostics required. Returns true if
5250/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005251void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005252 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005253 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5254 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005255 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005256
5257 // C++ [class.copy]p3:
5258 // A declaration of a constructor for a class X is ill-formed if
5259 // its first parameter is of type (optionally cv-qualified) X and
5260 // either there are no other parameters or else all other
5261 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005262 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005263 ((Constructor->getNumParams() == 1) ||
5264 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005265 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5266 Constructor->getTemplateSpecializationKind()
5267 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005268 QualType ParamType = Constructor->getParamDecl(0)->getType();
5269 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5270 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005271 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005272 const char *ConstRef
5273 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5274 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005275 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005276 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005277
5278 // FIXME: Rather that making the constructor invalid, we should endeavor
5279 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005280 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005281 }
5282 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005283}
5284
John McCall15442822010-08-04 01:04:25 +00005285/// CheckDestructor - Checks a fully-formed destructor definition for
5286/// well-formedness, issuing any diagnostics required. Returns true
5287/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005288bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005289 CXXRecordDecl *RD = Destructor->getParent();
5290
5291 if (Destructor->isVirtual()) {
5292 SourceLocation Loc;
5293
5294 if (!Destructor->isImplicit())
5295 Loc = Destructor->getLocation();
5296 else
5297 Loc = RD->getLocation();
5298
5299 // If we have a virtual destructor, look up the deallocation function
5300 FunctionDecl *OperatorDelete = 0;
5301 DeclarationName Name =
5302 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005303 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005304 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005305
5306 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005307
5308 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005309 }
Anders Carlsson37909802009-11-30 21:24:50 +00005310
5311 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005312}
5313
Mike Stump1eb44332009-09-09 15:08:12 +00005314static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005315FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5316 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5317 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005318 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005319}
5320
Douglas Gregor42a552f2008-11-05 20:51:48 +00005321/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5322/// the well-formednes of the destructor declarator @p D with type @p
5323/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005324/// emit diagnostics and set the declarator to invalid. Even if this happens,
5325/// will be updated to reflect a well-formed type for the destructor and
5326/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005327QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005328 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005329 // C++ [class.dtor]p1:
5330 // [...] A typedef-name that names a class is a class-name
5331 // (7.1.3); however, a typedef-name that names a class shall not
5332 // be used as the identifier in the declarator for a destructor
5333 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005334 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005335 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005336 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005337 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005338 else if (const TemplateSpecializationType *TST =
5339 DeclaratorType->getAs<TemplateSpecializationType>())
5340 if (TST->isTypeAlias())
5341 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5342 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005343
5344 // C++ [class.dtor]p2:
5345 // A destructor is used to destroy objects of its class type. A
5346 // destructor takes no parameters, and no return type can be
5347 // specified for it (not even void). The address of a destructor
5348 // shall not be taken. A destructor shall not be static. A
5349 // destructor can be invoked for a const, volatile or const
5350 // volatile object. A destructor shall not be declared const,
5351 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005352 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005353 if (!D.isInvalidType())
5354 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5355 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005356 << SourceRange(D.getIdentifierLoc())
5357 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5358
John McCalld931b082010-08-26 03:08:43 +00005359 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005360 }
Chris Lattner65401802009-04-25 08:28:21 +00005361 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005362 // Destructors don't have return types, but the parser will
5363 // happily parse something like:
5364 //
5365 // class X {
5366 // float ~X();
5367 // };
5368 //
5369 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005370 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5371 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5372 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005373 }
Mike Stump1eb44332009-09-09 15:08:12 +00005374
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005375 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005376 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005377 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005378 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5379 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005380 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005381 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5382 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005383 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005384 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5385 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005386 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005387 }
5388
Douglas Gregorc938c162011-01-26 05:01:58 +00005389 // C++0x [class.dtor]p2:
5390 // A destructor shall not be declared with a ref-qualifier.
5391 if (FTI.hasRefQualifier()) {
5392 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5393 << FTI.RefQualifierIsLValueRef
5394 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5395 D.setInvalidType();
5396 }
5397
Douglas Gregor42a552f2008-11-05 20:51:48 +00005398 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005399 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005400 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5401
5402 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005403 FTI.freeArgs();
5404 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005405 }
5406
Mike Stump1eb44332009-09-09 15:08:12 +00005407 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005408 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005409 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005410 D.setInvalidType();
5411 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005412
5413 // Rebuild the function type "R" without any type qualifiers or
5414 // parameters (in case any of the errors above fired) and with
5415 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005416 // types.
John McCalle23cf432010-12-14 08:05:40 +00005417 if (!D.isInvalidType())
5418 return R;
5419
Douglas Gregord92ec472010-07-01 05:10:53 +00005420 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005421 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5422 EPI.Variadic = false;
5423 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005424 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005425 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005426}
5427
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005428/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5429/// well-formednes of the conversion function declarator @p D with
5430/// type @p R. If there are any errors in the declarator, this routine
5431/// will emit diagnostics and return true. Otherwise, it will return
5432/// false. Either way, the type @p R will be updated to reflect a
5433/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005434void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005435 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005436 // C++ [class.conv.fct]p1:
5437 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005438 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005439 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005440 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005441 if (!D.isInvalidType())
5442 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5443 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5444 << SourceRange(D.getIdentifierLoc());
5445 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005446 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005447 }
John McCalla3f81372010-04-13 00:04:31 +00005448
5449 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5450
Chris Lattner6e475012009-04-25 08:35:12 +00005451 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005452 // Conversion functions don't have return types, but the parser will
5453 // happily parse something like:
5454 //
5455 // class X {
5456 // float operator bool();
5457 // };
5458 //
5459 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005460 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5461 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5462 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005463 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005464 }
5465
John McCalla3f81372010-04-13 00:04:31 +00005466 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5467
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005468 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005469 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005470 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5471
5472 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005473 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005474 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005475 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005476 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005477 D.setInvalidType();
5478 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005479
John McCalla3f81372010-04-13 00:04:31 +00005480 // Diagnose "&operator bool()" and other such nonsense. This
5481 // is actually a gcc extension which we don't support.
5482 if (Proto->getResultType() != ConvType) {
5483 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5484 << Proto->getResultType();
5485 D.setInvalidType();
5486 ConvType = Proto->getResultType();
5487 }
5488
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005489 // C++ [class.conv.fct]p4:
5490 // The conversion-type-id shall not represent a function type nor
5491 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005492 if (ConvType->isArrayType()) {
5493 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5494 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005495 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005496 } else if (ConvType->isFunctionType()) {
5497 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5498 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005499 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005500 }
5501
5502 // Rebuild the function type "R" without any parameters (in case any
5503 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005504 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005505 if (D.isInvalidType())
5506 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005507
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005508 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005509 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005510 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005511 getLangOptions().CPlusPlus0x ?
5512 diag::warn_cxx98_compat_explicit_conversion_functions :
5513 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005514 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005515}
5516
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005517/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5518/// the declaration of the given C++ conversion function. This routine
5519/// is responsible for recording the conversion function in the C++
5520/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005521Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005522 assert(Conversion && "Expected to receive a conversion function declaration");
5523
Douglas Gregor9d350972008-12-12 08:25:50 +00005524 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005525
5526 // Make sure we aren't redeclaring the conversion function.
5527 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005528
5529 // C++ [class.conv.fct]p1:
5530 // [...] A conversion function is never used to convert a
5531 // (possibly cv-qualified) object to the (possibly cv-qualified)
5532 // same object type (or a reference to it), to a (possibly
5533 // cv-qualified) base class of that type (or a reference to it),
5534 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005535 // FIXME: Suppress this warning if the conversion function ends up being a
5536 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005537 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005538 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005539 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005540 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005541 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5542 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005543 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005544 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005545 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5546 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005547 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005548 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005549 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005550 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005551 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005552 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005553 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005554 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005555 }
5556
Douglas Gregore80622f2010-09-29 04:25:11 +00005557 if (FunctionTemplateDecl *ConversionTemplate
5558 = Conversion->getDescribedFunctionTemplate())
5559 return ConversionTemplate;
5560
John McCalld226f652010-08-21 09:40:31 +00005561 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005562}
5563
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005564//===----------------------------------------------------------------------===//
5565// Namespace Handling
5566//===----------------------------------------------------------------------===//
5567
John McCallea318642010-08-26 09:15:37 +00005568
5569
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005570/// ActOnStartNamespaceDef - This is called at the start of a namespace
5571/// definition.
John McCalld226f652010-08-21 09:40:31 +00005572Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005573 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005574 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005575 SourceLocation IdentLoc,
5576 IdentifierInfo *II,
5577 SourceLocation LBrace,
5578 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005579 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5580 // For anonymous namespace, take the location of the left brace.
5581 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005582 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005583 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005584 bool IsStd = false;
5585 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005586 Scope *DeclRegionScope = NamespcScope->getParent();
5587
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005588 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005589 if (II) {
5590 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005591 // The identifier in an original-namespace-definition shall not
5592 // have been previously defined in the declarative region in
5593 // which the original-namespace-definition appears. The
5594 // identifier in an original-namespace-definition is the name of
5595 // the namespace. Subsequently in that declarative region, it is
5596 // treated as an original-namespace-name.
5597 //
5598 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005599 // look through using directives, just look for any ordinary names.
5600
5601 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005602 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5603 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005604 NamedDecl *PrevDecl = 0;
5605 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005606 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005607 R.first != R.second; ++R.first) {
5608 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5609 PrevDecl = *R.first;
5610 break;
5611 }
5612 }
5613
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005614 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5615
5616 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005617 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005618 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005619 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005620 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005621 // The user probably just forgot the 'inline', so suggest that it
5622 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005623 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005624 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5625 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005626 Diag(Loc, diag::err_inline_namespace_mismatch)
5627 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005628 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005629 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5630
5631 IsInline = PrevNS->isInline();
5632 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005633 } else if (PrevDecl) {
5634 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005635 Diag(Loc, diag::err_redefinition_different_kind)
5636 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005637 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005638 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005639 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005640 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005641 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005642 // This is the first "real" definition of the namespace "std", so update
5643 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005644 PrevNS = getStdNamespace();
5645 IsStd = true;
5646 AddToKnown = !IsInline;
5647 } else {
5648 // We've seen this namespace for the first time.
5649 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005650 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005651 } else {
John McCall9aeed322009-10-01 00:25:31 +00005652 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005653
5654 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005655 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005656 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005657 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005658 } else {
5659 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005660 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005661 }
5662
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005663 if (PrevNS && IsInline != PrevNS->isInline()) {
5664 // inline-ness must match
5665 Diag(Loc, diag::err_inline_namespace_mismatch)
5666 << IsInline;
5667 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005668
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005669 // Recover by ignoring the new namespace's inline status.
5670 IsInline = PrevNS->isInline();
5671 }
5672 }
5673
5674 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5675 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005676 if (IsInvalid)
5677 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005678
5679 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005680
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005681 // FIXME: Should we be merging attributes?
5682 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5683 PushNamespaceVisibilityAttr(Attr);
5684
5685 if (IsStd)
5686 StdNamespace = Namespc;
5687 if (AddToKnown)
5688 KnownNamespaces[Namespc] = false;
5689
5690 if (II) {
5691 PushOnScopeChains(Namespc, DeclRegionScope);
5692 } else {
5693 // Link the anonymous namespace into its parent.
5694 DeclContext *Parent = CurContext->getRedeclContext();
5695 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5696 TU->setAnonymousNamespace(Namespc);
5697 } else {
5698 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005699 }
John McCall9aeed322009-10-01 00:25:31 +00005700
Douglas Gregora4181472010-03-24 00:46:35 +00005701 CurContext->addDecl(Namespc);
5702
John McCall9aeed322009-10-01 00:25:31 +00005703 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5704 // behaves as if it were replaced by
5705 // namespace unique { /* empty body */ }
5706 // using namespace unique;
5707 // namespace unique { namespace-body }
5708 // where all occurrences of 'unique' in a translation unit are
5709 // replaced by the same identifier and this identifier differs
5710 // from all other identifiers in the entire program.
5711
5712 // We just create the namespace with an empty name and then add an
5713 // implicit using declaration, just like the standard suggests.
5714 //
5715 // CodeGen enforces the "universally unique" aspect by giving all
5716 // declarations semantically contained within an anonymous
5717 // namespace internal linkage.
5718
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005719 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005720 UsingDirectiveDecl* UD
5721 = UsingDirectiveDecl::Create(Context, CurContext,
5722 /* 'using' */ LBrace,
5723 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005724 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005725 /* identifier */ SourceLocation(),
5726 Namespc,
5727 /* Ancestor */ CurContext);
5728 UD->setImplicit();
5729 CurContext->addDecl(UD);
5730 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005731 }
5732
5733 // Although we could have an invalid decl (i.e. the namespace name is a
5734 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005735 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5736 // for the namespace has the declarations that showed up in that particular
5737 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005738 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005739 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005740}
5741
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005742/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5743/// is a namespace alias, returns the namespace it points to.
5744static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5745 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5746 return AD->getNamespace();
5747 return dyn_cast_or_null<NamespaceDecl>(D);
5748}
5749
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005750/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5751/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005752void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005753 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5754 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005755 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005756 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005757 if (Namespc->hasAttr<VisibilityAttr>())
5758 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005759}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005760
John McCall384aff82010-08-25 07:42:41 +00005761CXXRecordDecl *Sema::getStdBadAlloc() const {
5762 return cast_or_null<CXXRecordDecl>(
5763 StdBadAlloc.get(Context.getExternalSource()));
5764}
5765
5766NamespaceDecl *Sema::getStdNamespace() const {
5767 return cast_or_null<NamespaceDecl>(
5768 StdNamespace.get(Context.getExternalSource()));
5769}
5770
Douglas Gregor66992202010-06-29 17:53:46 +00005771/// \brief Retrieve the special "std" namespace, which may require us to
5772/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005773NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005774 if (!StdNamespace) {
5775 // The "std" namespace has not yet been defined, so build one implicitly.
5776 StdNamespace = NamespaceDecl::Create(Context,
5777 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005778 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005779 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005780 &PP.getIdentifierTable().get("std"),
5781 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005782 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005783 }
5784
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005785 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005786}
5787
Sebastian Redl395e04d2012-01-17 22:49:33 +00005788bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5789 assert(getLangOptions().CPlusPlus &&
5790 "Looking for std::initializer_list outside of C++.");
5791
5792 // We're looking for implicit instantiations of
5793 // template <typename E> class std::initializer_list.
5794
5795 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5796 return false;
5797
Sebastian Redl84760e32012-01-17 22:49:58 +00005798 ClassTemplateDecl *Template = 0;
5799 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005800
Sebastian Redl84760e32012-01-17 22:49:58 +00005801 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005802
Sebastian Redl84760e32012-01-17 22:49:58 +00005803 ClassTemplateSpecializationDecl *Specialization =
5804 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5805 if (!Specialization)
5806 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005807
Sebastian Redl84760e32012-01-17 22:49:58 +00005808 if (Specialization->getSpecializationKind() != TSK_ImplicitInstantiation)
5809 return false;
5810
5811 Template = Specialization->getSpecializedTemplate();
5812 Arguments = Specialization->getTemplateArgs().data();
5813 } else if (const TemplateSpecializationType *TST =
5814 Ty->getAs<TemplateSpecializationType>()) {
5815 Template = dyn_cast_or_null<ClassTemplateDecl>(
5816 TST->getTemplateName().getAsTemplateDecl());
5817 Arguments = TST->getArgs();
5818 }
5819 if (!Template)
5820 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005821
5822 if (!StdInitializerList) {
5823 // Haven't recognized std::initializer_list yet, maybe this is it.
5824 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5825 if (TemplateClass->getIdentifier() !=
5826 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005827 !getStdNamespace()->InEnclosingNamespaceSetOf(
5828 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005829 return false;
5830 // This is a template called std::initializer_list, but is it the right
5831 // template?
5832 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005833 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005834 return false;
5835 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5836 return false;
5837
5838 // It's the right template.
5839 StdInitializerList = Template;
5840 }
5841
5842 if (Template != StdInitializerList)
5843 return false;
5844
5845 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005846 if (Element)
5847 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005848 return true;
5849}
5850
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005851static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5852 NamespaceDecl *Std = S.getStdNamespace();
5853 if (!Std) {
5854 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5855 return 0;
5856 }
5857
5858 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5859 Loc, Sema::LookupOrdinaryName);
5860 if (!S.LookupQualifiedName(Result, Std)) {
5861 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5862 return 0;
5863 }
5864 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5865 if (!Template) {
5866 Result.suppressDiagnostics();
5867 // We found something weird. Complain about the first thing we found.
5868 NamedDecl *Found = *Result.begin();
5869 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5870 return 0;
5871 }
5872
5873 // We found some template called std::initializer_list. Now verify that it's
5874 // correct.
5875 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005876 if (Params->getMinRequiredArguments() != 1 ||
5877 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005878 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5879 return 0;
5880 }
5881
5882 return Template;
5883}
5884
5885QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5886 if (!StdInitializerList) {
5887 StdInitializerList = LookupStdInitializerList(*this, Loc);
5888 if (!StdInitializerList)
5889 return QualType();
5890 }
5891
5892 TemplateArgumentListInfo Args(Loc, Loc);
5893 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5894 Context.getTrivialTypeSourceInfo(Element,
5895 Loc)));
5896 return Context.getCanonicalType(
5897 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5898}
5899
Sebastian Redl98d36062012-01-17 22:50:14 +00005900bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5901 // C++ [dcl.init.list]p2:
5902 // A constructor is an initializer-list constructor if its first parameter
5903 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5904 // std::initializer_list<E> for some type E, and either there are no other
5905 // parameters or else all other parameters have default arguments.
5906 if (Ctor->getNumParams() < 1 ||
5907 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5908 return false;
5909
5910 QualType ArgType = Ctor->getParamDecl(0)->getType();
5911 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5912 ArgType = RT->getPointeeType().getUnqualifiedType();
5913
5914 return isStdInitializerList(ArgType, 0);
5915}
5916
Douglas Gregor9172aa62011-03-26 22:25:30 +00005917/// \brief Determine whether a using statement is in a context where it will be
5918/// apply in all contexts.
5919static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5920 switch (CurContext->getDeclKind()) {
5921 case Decl::TranslationUnit:
5922 return true;
5923 case Decl::LinkageSpec:
5924 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5925 default:
5926 return false;
5927 }
5928}
5929
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005930namespace {
5931
5932// Callback to only accept typo corrections that are namespaces.
5933class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5934 public:
5935 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5936 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5937 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5938 }
5939 return false;
5940 }
5941};
5942
5943}
5944
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005945static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5946 CXXScopeSpec &SS,
5947 SourceLocation IdentLoc,
5948 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005949 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005950 R.clear();
5951 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005952 R.getLookupKind(), Sc, &SS,
5953 &Validator)) {
5954 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5955 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5956 if (DeclContext *DC = S.computeDeclContext(SS, false))
5957 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5958 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5959 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5960 else
5961 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5962 << Ident << CorrectedQuotedStr
5963 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005964
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005965 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5966 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005967
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005968 Ident = Corrected.getCorrectionAsIdentifierInfo();
5969 R.addDecl(Corrected.getCorrectionDecl());
5970 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005971 }
5972 return false;
5973}
5974
John McCalld226f652010-08-21 09:40:31 +00005975Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005976 SourceLocation UsingLoc,
5977 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005978 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005979 SourceLocation IdentLoc,
5980 IdentifierInfo *NamespcName,
5981 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005982 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5983 assert(NamespcName && "Invalid NamespcName.");
5984 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005985
5986 // This can only happen along a recovery path.
5987 while (S->getFlags() & Scope::TemplateParamScope)
5988 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005989 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005990
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005991 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005992 NestedNameSpecifier *Qualifier = 0;
5993 if (SS.isSet())
5994 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5995
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005996 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005997 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5998 LookupParsedName(R, S, &SS);
5999 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006000 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006001
Douglas Gregor66992202010-06-29 17:53:46 +00006002 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006003 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006004 // Allow "using namespace std;" or "using namespace ::std;" even if
6005 // "std" hasn't been defined yet, for GCC compatibility.
6006 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6007 NamespcName->isStr("std")) {
6008 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006009 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006010 R.resolveKind();
6011 }
6012 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006013 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006014 }
6015
John McCallf36e02d2009-10-09 21:13:30 +00006016 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006017 NamedDecl *Named = R.getFoundDecl();
6018 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6019 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006020 // C++ [namespace.udir]p1:
6021 // A using-directive specifies that the names in the nominated
6022 // namespace can be used in the scope in which the
6023 // using-directive appears after the using-directive. During
6024 // unqualified name lookup (3.4.1), the names appear as if they
6025 // were declared in the nearest enclosing namespace which
6026 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006027 // namespace. [Note: in this context, "contains" means "contains
6028 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006029
6030 // Find enclosing context containing both using-directive and
6031 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006032 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006033 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6034 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6035 CommonAncestor = CommonAncestor->getParent();
6036
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006037 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006038 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006039 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006040
Douglas Gregor9172aa62011-03-26 22:25:30 +00006041 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006042 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006043 Diag(IdentLoc, diag::warn_using_directive_in_header);
6044 }
6045
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006046 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006047 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006048 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006049 }
6050
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006051 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006052 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006053}
6054
6055void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6056 // If scope has associated entity, then using directive is at namespace
6057 // or translation unit scope. We add UsingDirectiveDecls, into
6058 // it's lookup structure.
6059 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006060 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006061 else
6062 // Otherwise it is block-sope. using-directives will affect lookup
6063 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006064 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006065}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006066
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006067
John McCalld226f652010-08-21 09:40:31 +00006068Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006069 AccessSpecifier AS,
6070 bool HasUsingKeyword,
6071 SourceLocation UsingLoc,
6072 CXXScopeSpec &SS,
6073 UnqualifiedId &Name,
6074 AttributeList *AttrList,
6075 bool IsTypeName,
6076 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006077 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006078
Douglas Gregor12c118a2009-11-04 16:30:06 +00006079 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006080 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006081 case UnqualifiedId::IK_Identifier:
6082 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006083 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006084 case UnqualifiedId::IK_ConversionFunctionId:
6085 break;
6086
6087 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006088 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006089 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006090 Diag(Name.getSourceRange().getBegin(),
6091 getLangOptions().CPlusPlus0x ?
6092 diag::warn_cxx98_compat_using_decl_constructor :
6093 diag::err_using_decl_constructor)
6094 << SS.getRange();
6095
John McCall604e7f12009-12-08 07:46:18 +00006096 if (getLangOptions().CPlusPlus0x) break;
6097
John McCalld226f652010-08-21 09:40:31 +00006098 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006099
6100 case UnqualifiedId::IK_DestructorName:
6101 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6102 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006103 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006104
6105 case UnqualifiedId::IK_TemplateId:
6106 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6107 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006108 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006109 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006110
6111 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6112 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006113 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006114 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006115
John McCall60fa3cf2009-12-11 02:10:03 +00006116 // Warn about using declarations.
6117 // TODO: store that the declaration was written without 'using' and
6118 // talk about access decls instead of using decls in the
6119 // diagnostics.
6120 if (!HasUsingKeyword) {
6121 UsingLoc = Name.getSourceRange().getBegin();
6122
6123 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006124 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006125 }
6126
Douglas Gregor56c04582010-12-16 00:46:58 +00006127 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6128 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6129 return 0;
6130
John McCall9488ea12009-11-17 05:59:44 +00006131 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006132 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006133 /* IsInstantiation */ false,
6134 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006135 if (UD)
6136 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006137
John McCalld226f652010-08-21 09:40:31 +00006138 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006139}
6140
Douglas Gregor09acc982010-07-07 23:08:52 +00006141/// \brief Determine whether a using declaration considers the given
6142/// declarations as "equivalent", e.g., if they are redeclarations of
6143/// the same entity or are both typedefs of the same type.
6144static bool
6145IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6146 bool &SuppressRedeclaration) {
6147 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6148 SuppressRedeclaration = false;
6149 return true;
6150 }
6151
Richard Smith162e1c12011-04-15 14:24:37 +00006152 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6153 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006154 SuppressRedeclaration = true;
6155 return Context.hasSameType(TD1->getUnderlyingType(),
6156 TD2->getUnderlyingType());
6157 }
6158
6159 return false;
6160}
6161
6162
John McCall9f54ad42009-12-10 09:41:52 +00006163/// Determines whether to create a using shadow decl for a particular
6164/// decl, given the set of decls existing prior to this using lookup.
6165bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6166 const LookupResult &Previous) {
6167 // Diagnose finding a decl which is not from a base class of the
6168 // current class. We do this now because there are cases where this
6169 // function will silently decide not to build a shadow decl, which
6170 // will pre-empt further diagnostics.
6171 //
6172 // We don't need to do this in C++0x because we do the check once on
6173 // the qualifier.
6174 //
6175 // FIXME: diagnose the following if we care enough:
6176 // struct A { int foo; };
6177 // struct B : A { using A::foo; };
6178 // template <class T> struct C : A {};
6179 // template <class T> struct D : C<T> { using B::foo; } // <---
6180 // This is invalid (during instantiation) in C++03 because B::foo
6181 // resolves to the using decl in B, which is not a base class of D<T>.
6182 // We can't diagnose it immediately because C<T> is an unknown
6183 // specialization. The UsingShadowDecl in D<T> then points directly
6184 // to A::foo, which will look well-formed when we instantiate.
6185 // The right solution is to not collapse the shadow-decl chain.
6186 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6187 DeclContext *OrigDC = Orig->getDeclContext();
6188
6189 // Handle enums and anonymous structs.
6190 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6191 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6192 while (OrigRec->isAnonymousStructOrUnion())
6193 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6194
6195 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6196 if (OrigDC == CurContext) {
6197 Diag(Using->getLocation(),
6198 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006199 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006200 Diag(Orig->getLocation(), diag::note_using_decl_target);
6201 return true;
6202 }
6203
Douglas Gregordc355712011-02-25 00:36:19 +00006204 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006205 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006206 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006207 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006208 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006209 Diag(Orig->getLocation(), diag::note_using_decl_target);
6210 return true;
6211 }
6212 }
6213
6214 if (Previous.empty()) return false;
6215
6216 NamedDecl *Target = Orig;
6217 if (isa<UsingShadowDecl>(Target))
6218 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6219
John McCalld7533ec2009-12-11 02:33:26 +00006220 // If the target happens to be one of the previous declarations, we
6221 // don't have a conflict.
6222 //
6223 // FIXME: but we might be increasing its access, in which case we
6224 // should redeclare it.
6225 NamedDecl *NonTag = 0, *Tag = 0;
6226 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6227 I != E; ++I) {
6228 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006229 bool Result;
6230 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6231 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006232
6233 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6234 }
6235
John McCall9f54ad42009-12-10 09:41:52 +00006236 if (Target->isFunctionOrFunctionTemplate()) {
6237 FunctionDecl *FD;
6238 if (isa<FunctionTemplateDecl>(Target))
6239 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6240 else
6241 FD = cast<FunctionDecl>(Target);
6242
6243 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006244 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006245 case Ovl_Overload:
6246 return false;
6247
6248 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006249 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006250 break;
6251
6252 // We found a decl with the exact signature.
6253 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006254 // If we're in a record, we want to hide the target, so we
6255 // return true (without a diagnostic) to tell the caller not to
6256 // build a shadow decl.
6257 if (CurContext->isRecord())
6258 return true;
6259
6260 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006261 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006262 break;
6263 }
6264
6265 Diag(Target->getLocation(), diag::note_using_decl_target);
6266 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6267 return true;
6268 }
6269
6270 // Target is not a function.
6271
John McCall9f54ad42009-12-10 09:41:52 +00006272 if (isa<TagDecl>(Target)) {
6273 // No conflict between a tag and a non-tag.
6274 if (!Tag) return false;
6275
John McCall41ce66f2009-12-10 19:51:03 +00006276 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006277 Diag(Target->getLocation(), diag::note_using_decl_target);
6278 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6279 return true;
6280 }
6281
6282 // No conflict between a tag and a non-tag.
6283 if (!NonTag) return false;
6284
John McCall41ce66f2009-12-10 19:51:03 +00006285 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006286 Diag(Target->getLocation(), diag::note_using_decl_target);
6287 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6288 return true;
6289}
6290
John McCall9488ea12009-11-17 05:59:44 +00006291/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006292UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006293 UsingDecl *UD,
6294 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006295
6296 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006297 NamedDecl *Target = Orig;
6298 if (isa<UsingShadowDecl>(Target)) {
6299 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6300 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006301 }
6302
6303 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006304 = UsingShadowDecl::Create(Context, CurContext,
6305 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006306 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006307
6308 Shadow->setAccess(UD->getAccess());
6309 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6310 Shadow->setInvalidDecl();
6311
John McCall9488ea12009-11-17 05:59:44 +00006312 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006313 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006314 else
John McCall604e7f12009-12-08 07:46:18 +00006315 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006316
John McCall604e7f12009-12-08 07:46:18 +00006317
John McCall9f54ad42009-12-10 09:41:52 +00006318 return Shadow;
6319}
John McCall604e7f12009-12-08 07:46:18 +00006320
John McCall9f54ad42009-12-10 09:41:52 +00006321/// Hides a using shadow declaration. This is required by the current
6322/// using-decl implementation when a resolvable using declaration in a
6323/// class is followed by a declaration which would hide or override
6324/// one or more of the using decl's targets; for example:
6325///
6326/// struct Base { void foo(int); };
6327/// struct Derived : Base {
6328/// using Base::foo;
6329/// void foo(int);
6330/// };
6331///
6332/// The governing language is C++03 [namespace.udecl]p12:
6333///
6334/// When a using-declaration brings names from a base class into a
6335/// derived class scope, member functions in the derived class
6336/// override and/or hide member functions with the same name and
6337/// parameter types in a base class (rather than conflicting).
6338///
6339/// There are two ways to implement this:
6340/// (1) optimistically create shadow decls when they're not hidden
6341/// by existing declarations, or
6342/// (2) don't create any shadow decls (or at least don't make them
6343/// visible) until we've fully parsed/instantiated the class.
6344/// The problem with (1) is that we might have to retroactively remove
6345/// a shadow decl, which requires several O(n) operations because the
6346/// decl structures are (very reasonably) not designed for removal.
6347/// (2) avoids this but is very fiddly and phase-dependent.
6348void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006349 if (Shadow->getDeclName().getNameKind() ==
6350 DeclarationName::CXXConversionFunctionName)
6351 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6352
John McCall9f54ad42009-12-10 09:41:52 +00006353 // Remove it from the DeclContext...
6354 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006355
John McCall9f54ad42009-12-10 09:41:52 +00006356 // ...and the scope, if applicable...
6357 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006358 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006359 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006360 }
6361
John McCall9f54ad42009-12-10 09:41:52 +00006362 // ...and the using decl.
6363 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6364
6365 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006366 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006367}
6368
John McCall7ba107a2009-11-18 02:36:19 +00006369/// Builds a using declaration.
6370///
6371/// \param IsInstantiation - Whether this call arises from an
6372/// instantiation of an unresolved using declaration. We treat
6373/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006374NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6375 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006376 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006377 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006378 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006379 bool IsInstantiation,
6380 bool IsTypeName,
6381 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006382 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006383 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006384 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006385
Anders Carlsson550b14b2009-08-28 05:49:21 +00006386 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006387
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006388 if (SS.isEmpty()) {
6389 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006390 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006391 }
Mike Stump1eb44332009-09-09 15:08:12 +00006392
John McCall9f54ad42009-12-10 09:41:52 +00006393 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006394 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006395 ForRedeclaration);
6396 Previous.setHideTags(false);
6397 if (S) {
6398 LookupName(Previous, S);
6399
6400 // It is really dumb that we have to do this.
6401 LookupResult::Filter F = Previous.makeFilter();
6402 while (F.hasNext()) {
6403 NamedDecl *D = F.next();
6404 if (!isDeclInScope(D, CurContext, S))
6405 F.erase();
6406 }
6407 F.done();
6408 } else {
6409 assert(IsInstantiation && "no scope in non-instantiation");
6410 assert(CurContext->isRecord() && "scope not record in instantiation");
6411 LookupQualifiedName(Previous, CurContext);
6412 }
6413
John McCall9f54ad42009-12-10 09:41:52 +00006414 // Check for invalid redeclarations.
6415 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6416 return 0;
6417
6418 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006419 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6420 return 0;
6421
John McCallaf8e6ed2009-11-12 03:15:40 +00006422 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006423 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006424 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006425 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006426 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006427 // FIXME: not all declaration name kinds are legal here
6428 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6429 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006430 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006431 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006432 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006433 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6434 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006435 }
John McCalled976492009-12-04 22:46:56 +00006436 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006437 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6438 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006439 }
John McCalled976492009-12-04 22:46:56 +00006440 D->setAccess(AS);
6441 CurContext->addDecl(D);
6442
6443 if (!LookupContext) return D;
6444 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006445
John McCall77bb1aa2010-05-01 00:40:08 +00006446 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006447 UD->setInvalidDecl();
6448 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006449 }
6450
Sebastian Redlf677ea32011-02-05 19:23:19 +00006451 // Constructor inheriting using decls get special treatment.
6452 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006453 if (CheckInheritedConstructorUsingDecl(UD))
6454 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006455 return UD;
6456 }
6457
6458 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006459
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006460 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006461
John McCall604e7f12009-12-08 07:46:18 +00006462 // Unlike most lookups, we don't always want to hide tag
6463 // declarations: tag names are visible through the using declaration
6464 // even if hidden by ordinary names, *except* in a dependent context
6465 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006466 if (!IsInstantiation)
6467 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006468
John McCalla24dc2e2009-11-17 02:14:36 +00006469 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006470
John McCallf36e02d2009-10-09 21:13:30 +00006471 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006472 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006473 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006474 UD->setInvalidDecl();
6475 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006476 }
6477
John McCalled976492009-12-04 22:46:56 +00006478 if (R.isAmbiguous()) {
6479 UD->setInvalidDecl();
6480 return UD;
6481 }
Mike Stump1eb44332009-09-09 15:08:12 +00006482
John McCall7ba107a2009-11-18 02:36:19 +00006483 if (IsTypeName) {
6484 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006485 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006486 Diag(IdentLoc, diag::err_using_typename_non_type);
6487 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6488 Diag((*I)->getUnderlyingDecl()->getLocation(),
6489 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006490 UD->setInvalidDecl();
6491 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006492 }
6493 } else {
6494 // If we asked for a non-typename and we got a type, error out,
6495 // but only if this is an instantiation of an unresolved using
6496 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006497 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006498 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6499 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006500 UD->setInvalidDecl();
6501 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006502 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006503 }
6504
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006505 // C++0x N2914 [namespace.udecl]p6:
6506 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006507 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006508 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6509 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006510 UD->setInvalidDecl();
6511 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006512 }
Mike Stump1eb44332009-09-09 15:08:12 +00006513
John McCall9f54ad42009-12-10 09:41:52 +00006514 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6515 if (!CheckUsingShadowDecl(UD, *I, Previous))
6516 BuildUsingShadowDecl(S, UD, *I);
6517 }
John McCall9488ea12009-11-17 05:59:44 +00006518
6519 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006520}
6521
Sebastian Redlf677ea32011-02-05 19:23:19 +00006522/// Additional checks for a using declaration referring to a constructor name.
6523bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6524 if (UD->isTypeName()) {
6525 // FIXME: Cannot specify typename when specifying constructor
6526 return true;
6527 }
6528
Douglas Gregordc355712011-02-25 00:36:19 +00006529 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006530 assert(SourceType &&
6531 "Using decl naming constructor doesn't have type in scope spec.");
6532 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6533
6534 // Check whether the named type is a direct base class.
6535 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6536 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6537 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6538 BaseIt != BaseE; ++BaseIt) {
6539 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6540 if (CanonicalSourceType == BaseType)
6541 break;
6542 }
6543
6544 if (BaseIt == BaseE) {
6545 // Did not find SourceType in the bases.
6546 Diag(UD->getUsingLocation(),
6547 diag::err_using_decl_constructor_not_in_direct_base)
6548 << UD->getNameInfo().getSourceRange()
6549 << QualType(SourceType, 0) << TargetClass;
6550 return true;
6551 }
6552
6553 BaseIt->setInheritConstructors();
6554
6555 return false;
6556}
6557
John McCall9f54ad42009-12-10 09:41:52 +00006558/// Checks that the given using declaration is not an invalid
6559/// redeclaration. Note that this is checking only for the using decl
6560/// itself, not for any ill-formedness among the UsingShadowDecls.
6561bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6562 bool isTypeName,
6563 const CXXScopeSpec &SS,
6564 SourceLocation NameLoc,
6565 const LookupResult &Prev) {
6566 // C++03 [namespace.udecl]p8:
6567 // C++0x [namespace.udecl]p10:
6568 // A using-declaration is a declaration and can therefore be used
6569 // repeatedly where (and only where) multiple declarations are
6570 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006571 //
John McCall8a726212010-11-29 18:01:58 +00006572 // That's in non-member contexts.
6573 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006574 return false;
6575
6576 NestedNameSpecifier *Qual
6577 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6578
6579 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6580 NamedDecl *D = *I;
6581
6582 bool DTypename;
6583 NestedNameSpecifier *DQual;
6584 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6585 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006586 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006587 } else if (UnresolvedUsingValueDecl *UD
6588 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6589 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006590 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006591 } else if (UnresolvedUsingTypenameDecl *UD
6592 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6593 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006594 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006595 } else continue;
6596
6597 // using decls differ if one says 'typename' and the other doesn't.
6598 // FIXME: non-dependent using decls?
6599 if (isTypeName != DTypename) continue;
6600
6601 // using decls differ if they name different scopes (but note that
6602 // template instantiation can cause this check to trigger when it
6603 // didn't before instantiation).
6604 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6605 Context.getCanonicalNestedNameSpecifier(DQual))
6606 continue;
6607
6608 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006609 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006610 return true;
6611 }
6612
6613 return false;
6614}
6615
John McCall604e7f12009-12-08 07:46:18 +00006616
John McCalled976492009-12-04 22:46:56 +00006617/// Checks that the given nested-name qualifier used in a using decl
6618/// in the current context is appropriately related to the current
6619/// scope. If an error is found, diagnoses it and returns true.
6620bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6621 const CXXScopeSpec &SS,
6622 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006623 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006624
John McCall604e7f12009-12-08 07:46:18 +00006625 if (!CurContext->isRecord()) {
6626 // C++03 [namespace.udecl]p3:
6627 // C++0x [namespace.udecl]p8:
6628 // A using-declaration for a class member shall be a member-declaration.
6629
6630 // If we weren't able to compute a valid scope, it must be a
6631 // dependent class scope.
6632 if (!NamedContext || NamedContext->isRecord()) {
6633 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6634 << SS.getRange();
6635 return true;
6636 }
6637
6638 // Otherwise, everything is known to be fine.
6639 return false;
6640 }
6641
6642 // The current scope is a record.
6643
6644 // If the named context is dependent, we can't decide much.
6645 if (!NamedContext) {
6646 // FIXME: in C++0x, we can diagnose if we can prove that the
6647 // nested-name-specifier does not refer to a base class, which is
6648 // still possible in some cases.
6649
6650 // Otherwise we have to conservatively report that things might be
6651 // okay.
6652 return false;
6653 }
6654
6655 if (!NamedContext->isRecord()) {
6656 // Ideally this would point at the last name in the specifier,
6657 // but we don't have that level of source info.
6658 Diag(SS.getRange().getBegin(),
6659 diag::err_using_decl_nested_name_specifier_is_not_class)
6660 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6661 return true;
6662 }
6663
Douglas Gregor6fb07292010-12-21 07:41:49 +00006664 if (!NamedContext->isDependentContext() &&
6665 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6666 return true;
6667
John McCall604e7f12009-12-08 07:46:18 +00006668 if (getLangOptions().CPlusPlus0x) {
6669 // C++0x [namespace.udecl]p3:
6670 // In a using-declaration used as a member-declaration, the
6671 // nested-name-specifier shall name a base class of the class
6672 // being defined.
6673
6674 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6675 cast<CXXRecordDecl>(NamedContext))) {
6676 if (CurContext == NamedContext) {
6677 Diag(NameLoc,
6678 diag::err_using_decl_nested_name_specifier_is_current_class)
6679 << SS.getRange();
6680 return true;
6681 }
6682
6683 Diag(SS.getRange().getBegin(),
6684 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6685 << (NestedNameSpecifier*) SS.getScopeRep()
6686 << cast<CXXRecordDecl>(CurContext)
6687 << SS.getRange();
6688 return true;
6689 }
6690
6691 return false;
6692 }
6693
6694 // C++03 [namespace.udecl]p4:
6695 // A using-declaration used as a member-declaration shall refer
6696 // to a member of a base class of the class being defined [etc.].
6697
6698 // Salient point: SS doesn't have to name a base class as long as
6699 // lookup only finds members from base classes. Therefore we can
6700 // diagnose here only if we can prove that that can't happen,
6701 // i.e. if the class hierarchies provably don't intersect.
6702
6703 // TODO: it would be nice if "definitely valid" results were cached
6704 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6705 // need to be repeated.
6706
6707 struct UserData {
6708 llvm::DenseSet<const CXXRecordDecl*> Bases;
6709
6710 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6711 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6712 Data->Bases.insert(Base);
6713 return true;
6714 }
6715
6716 bool hasDependentBases(const CXXRecordDecl *Class) {
6717 return !Class->forallBases(collect, this);
6718 }
6719
6720 /// Returns true if the base is dependent or is one of the
6721 /// accumulated base classes.
6722 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6723 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6724 return !Data->Bases.count(Base);
6725 }
6726
6727 bool mightShareBases(const CXXRecordDecl *Class) {
6728 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6729 }
6730 };
6731
6732 UserData Data;
6733
6734 // Returns false if we find a dependent base.
6735 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6736 return false;
6737
6738 // Returns false if the class has a dependent base or if it or one
6739 // of its bases is present in the base set of the current context.
6740 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6741 return false;
6742
6743 Diag(SS.getRange().getBegin(),
6744 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6745 << (NestedNameSpecifier*) SS.getScopeRep()
6746 << cast<CXXRecordDecl>(CurContext)
6747 << SS.getRange();
6748
6749 return true;
John McCalled976492009-12-04 22:46:56 +00006750}
6751
Richard Smith162e1c12011-04-15 14:24:37 +00006752Decl *Sema::ActOnAliasDeclaration(Scope *S,
6753 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006754 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006755 SourceLocation UsingLoc,
6756 UnqualifiedId &Name,
6757 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006758 // Skip up to the relevant declaration scope.
6759 while (S->getFlags() & Scope::TemplateParamScope)
6760 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006761 assert((S->getFlags() & Scope::DeclScope) &&
6762 "got alias-declaration outside of declaration scope");
6763
6764 if (Type.isInvalid())
6765 return 0;
6766
6767 bool Invalid = false;
6768 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6769 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006770 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006771
6772 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6773 return 0;
6774
6775 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006776 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006777 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006778 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6779 TInfo->getTypeLoc().getBeginLoc());
6780 }
Richard Smith162e1c12011-04-15 14:24:37 +00006781
6782 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6783 LookupName(Previous, S);
6784
6785 // Warn about shadowing the name of a template parameter.
6786 if (Previous.isSingleResult() &&
6787 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006788 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006789 Previous.clear();
6790 }
6791
6792 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6793 "name in alias declaration must be an identifier");
6794 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6795 Name.StartLocation,
6796 Name.Identifier, TInfo);
6797
6798 NewTD->setAccess(AS);
6799
6800 if (Invalid)
6801 NewTD->setInvalidDecl();
6802
Richard Smith3e4c6c42011-05-05 21:57:07 +00006803 CheckTypedefForVariablyModifiedType(S, NewTD);
6804 Invalid |= NewTD->isInvalidDecl();
6805
Richard Smith162e1c12011-04-15 14:24:37 +00006806 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006807
6808 NamedDecl *NewND;
6809 if (TemplateParamLists.size()) {
6810 TypeAliasTemplateDecl *OldDecl = 0;
6811 TemplateParameterList *OldTemplateParams = 0;
6812
6813 if (TemplateParamLists.size() != 1) {
6814 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6815 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6816 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6817 }
6818 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6819
6820 // Only consider previous declarations in the same scope.
6821 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6822 /*ExplicitInstantiationOrSpecialization*/false);
6823 if (!Previous.empty()) {
6824 Redeclaration = true;
6825
6826 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6827 if (!OldDecl && !Invalid) {
6828 Diag(UsingLoc, diag::err_redefinition_different_kind)
6829 << Name.Identifier;
6830
6831 NamedDecl *OldD = Previous.getRepresentativeDecl();
6832 if (OldD->getLocation().isValid())
6833 Diag(OldD->getLocation(), diag::note_previous_definition);
6834
6835 Invalid = true;
6836 }
6837
6838 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6839 if (TemplateParameterListsAreEqual(TemplateParams,
6840 OldDecl->getTemplateParameters(),
6841 /*Complain=*/true,
6842 TPL_TemplateMatch))
6843 OldTemplateParams = OldDecl->getTemplateParameters();
6844 else
6845 Invalid = true;
6846
6847 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6848 if (!Invalid &&
6849 !Context.hasSameType(OldTD->getUnderlyingType(),
6850 NewTD->getUnderlyingType())) {
6851 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6852 // but we can't reasonably accept it.
6853 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6854 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6855 if (OldTD->getLocation().isValid())
6856 Diag(OldTD->getLocation(), diag::note_previous_definition);
6857 Invalid = true;
6858 }
6859 }
6860 }
6861
6862 // Merge any previous default template arguments into our parameters,
6863 // and check the parameter list.
6864 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6865 TPC_TypeAliasTemplate))
6866 return 0;
6867
6868 TypeAliasTemplateDecl *NewDecl =
6869 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6870 Name.Identifier, TemplateParams,
6871 NewTD);
6872
6873 NewDecl->setAccess(AS);
6874
6875 if (Invalid)
6876 NewDecl->setInvalidDecl();
6877 else if (OldDecl)
6878 NewDecl->setPreviousDeclaration(OldDecl);
6879
6880 NewND = NewDecl;
6881 } else {
6882 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6883 NewND = NewTD;
6884 }
Richard Smith162e1c12011-04-15 14:24:37 +00006885
6886 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006887 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006888
Richard Smith3e4c6c42011-05-05 21:57:07 +00006889 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006890}
6891
John McCalld226f652010-08-21 09:40:31 +00006892Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006893 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006894 SourceLocation AliasLoc,
6895 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006896 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006897 SourceLocation IdentLoc,
6898 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006899
Anders Carlsson81c85c42009-03-28 23:53:49 +00006900 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006901 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6902 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006903
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006904 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006905 NamedDecl *PrevDecl
6906 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6907 ForRedeclaration);
6908 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6909 PrevDecl = 0;
6910
6911 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006912 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006913 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006914 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006915 // FIXME: At some point, we'll want to create the (redundant)
6916 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006917 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006918 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006919 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006920 }
Mike Stump1eb44332009-09-09 15:08:12 +00006921
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006922 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6923 diag::err_redefinition_different_kind;
6924 Diag(AliasLoc, DiagID) << Alias;
6925 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006926 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006927 }
6928
John McCalla24dc2e2009-11-17 02:14:36 +00006929 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006930 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006931
John McCallf36e02d2009-10-09 21:13:30 +00006932 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006933 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006934 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006935 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006936 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006937 }
Mike Stump1eb44332009-09-09 15:08:12 +00006938
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006939 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006940 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006941 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006942 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006943
John McCall3dbd3d52010-02-16 06:53:13 +00006944 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006945 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006946}
6947
Douglas Gregor39957dc2010-05-01 15:04:51 +00006948namespace {
6949 /// \brief Scoped object used to handle the state changes required in Sema
6950 /// to implicitly define the body of a C++ member function;
6951 class ImplicitlyDefinedFunctionScope {
6952 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006953 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006954
6955 public:
6956 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006957 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006958 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006959 S.PushFunctionScope();
6960 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6961 }
6962
6963 ~ImplicitlyDefinedFunctionScope() {
6964 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006965 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006966 }
6967 };
6968}
6969
Sean Hunt001cad92011-05-10 00:49:42 +00006970Sema::ImplicitExceptionSpecification
6971Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006972 // C++ [except.spec]p14:
6973 // An implicitly declared special member function (Clause 12) shall have an
6974 // exception-specification. [...]
6975 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006976 if (ClassDecl->isInvalidDecl())
6977 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006978
Sebastian Redl60618fa2011-03-12 11:50:43 +00006979 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006980 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6981 BEnd = ClassDecl->bases_end();
6982 B != BEnd; ++B) {
6983 if (B->isVirtual()) // Handled below.
6984 continue;
6985
Douglas Gregor18274032010-07-03 00:47:00 +00006986 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6987 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006988 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6989 // If this is a deleted function, add it anyway. This might be conformant
6990 // with the standard. This might not. I'm not sure. It might not matter.
6991 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006992 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006993 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006994 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006995
6996 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006997 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6998 BEnd = ClassDecl->vbases_end();
6999 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007000 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7001 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007002 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7003 // If this is a deleted function, add it anyway. This might be conformant
7004 // with the standard. This might not. I'm not sure. It might not matter.
7005 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007006 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007007 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007008 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007009
7010 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007011 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7012 FEnd = ClassDecl->field_end();
7013 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007014 if (F->hasInClassInitializer()) {
7015 if (Expr *E = F->getInClassInitializer())
7016 ExceptSpec.CalledExpr(E);
7017 else if (!F->isInvalidDecl())
7018 ExceptSpec.SetDelayed();
7019 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007020 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007021 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7022 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7023 // If this is a deleted function, add it anyway. This might be conformant
7024 // with the standard. This might not. I'm not sure. It might not matter.
7025 // In particular, the problem is that this function never gets called. It
7026 // might just be ill-formed because this function attempts to refer to
7027 // a deleted function here.
7028 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007029 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007030 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007031 }
John McCalle23cf432010-12-14 08:05:40 +00007032
Sean Hunt001cad92011-05-10 00:49:42 +00007033 return ExceptSpec;
7034}
7035
7036CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7037 CXXRecordDecl *ClassDecl) {
7038 // C++ [class.ctor]p5:
7039 // A default constructor for a class X is a constructor of class X
7040 // that can be called without an argument. If there is no
7041 // user-declared constructor for class X, a default constructor is
7042 // implicitly declared. An implicitly-declared default constructor
7043 // is an inline public member of its class.
7044 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7045 "Should not build implicit default constructor!");
7046
7047 ImplicitExceptionSpecification Spec =
7048 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7049 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007050
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007051 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007052 CanQualType ClassType
7053 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007054 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007055 DeclarationName Name
7056 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007057 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007058 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7059 Context, ClassDecl, ClassLoc, NameInfo,
7060 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7061 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7062 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7063 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007064 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007065 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007066 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007067 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007068
7069 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007070 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7071
Douglas Gregor23c94db2010-07-02 17:43:08 +00007072 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007073 PushOnScopeChains(DefaultCon, S, false);
7074 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007075
Sean Hunte16da072011-10-10 06:18:57 +00007076 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007077 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007078
Douglas Gregor32df23e2010-07-01 22:02:46 +00007079 return DefaultCon;
7080}
7081
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007082void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7083 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007084 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007085 !Constructor->doesThisDeclarationHaveABody() &&
7086 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007087 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007088
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007089 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007090 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007091
Douglas Gregor39957dc2010-05-01 15:04:51 +00007092 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007093 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007094 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007095 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007096 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007097 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007098 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007099 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007100 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007101
7102 SourceLocation Loc = Constructor->getLocation();
7103 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7104
7105 Constructor->setUsed();
7106 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007107
7108 if (ASTMutationListener *L = getASTMutationListener()) {
7109 L->CompletedImplicitDefinition(Constructor);
7110 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007111}
7112
Richard Smith7a614d82011-06-11 17:19:42 +00007113/// Get any existing defaulted default constructor for the given class. Do not
7114/// implicitly define one if it does not exist.
7115static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7116 CXXRecordDecl *D) {
7117 ASTContext &Context = Self.Context;
7118 QualType ClassType = Context.getTypeDeclType(D);
7119 DeclarationName ConstructorName
7120 = Context.DeclarationNames.getCXXConstructorName(
7121 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7122
7123 DeclContext::lookup_const_iterator Con, ConEnd;
7124 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7125 Con != ConEnd; ++Con) {
7126 // A function template cannot be defaulted.
7127 if (isa<FunctionTemplateDecl>(*Con))
7128 continue;
7129
7130 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7131 if (Constructor->isDefaultConstructor())
7132 return Constructor->isDefaulted() ? Constructor : 0;
7133 }
7134 return 0;
7135}
7136
7137void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7138 if (!D) return;
7139 AdjustDeclIfTemplate(D);
7140
7141 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7142 CXXConstructorDecl *CtorDecl
7143 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7144
7145 if (!CtorDecl) return;
7146
7147 // Compute the exception specification for the default constructor.
7148 const FunctionProtoType *CtorTy =
7149 CtorDecl->getType()->castAs<FunctionProtoType>();
7150 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7151 ImplicitExceptionSpecification Spec =
7152 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7153 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7154 assert(EPI.ExceptionSpecType != EST_Delayed);
7155
7156 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7157 }
7158
7159 // If the default constructor is explicitly defaulted, checking the exception
7160 // specification is deferred until now.
7161 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7162 !ClassDecl->isDependentType())
7163 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7164}
7165
Sebastian Redlf677ea32011-02-05 19:23:19 +00007166void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7167 // We start with an initial pass over the base classes to collect those that
7168 // inherit constructors from. If there are none, we can forgo all further
7169 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007170 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007171 BasesVector BasesToInheritFrom;
7172 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7173 BaseE = ClassDecl->bases_end();
7174 BaseIt != BaseE; ++BaseIt) {
7175 if (BaseIt->getInheritConstructors()) {
7176 QualType Base = BaseIt->getType();
7177 if (Base->isDependentType()) {
7178 // If we inherit constructors from anything that is dependent, just
7179 // abort processing altogether. We'll get another chance for the
7180 // instantiations.
7181 return;
7182 }
7183 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7184 }
7185 }
7186 if (BasesToInheritFrom.empty())
7187 return;
7188
7189 // Now collect the constructors that we already have in the current class.
7190 // Those take precedence over inherited constructors.
7191 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7192 // unless there is a user-declared constructor with the same signature in
7193 // the class where the using-declaration appears.
7194 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7195 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7196 CtorE = ClassDecl->ctor_end();
7197 CtorIt != CtorE; ++CtorIt) {
7198 ExistingConstructors.insert(
7199 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7200 }
7201
7202 Scope *S = getScopeForContext(ClassDecl);
7203 DeclarationName CreatedCtorName =
7204 Context.DeclarationNames.getCXXConstructorName(
7205 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7206
7207 // Now comes the true work.
7208 // First, we keep a map from constructor types to the base that introduced
7209 // them. Needed for finding conflicting constructors. We also keep the
7210 // actually inserted declarations in there, for pretty diagnostics.
7211 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7212 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7213 ConstructorToSourceMap InheritedConstructors;
7214 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7215 BaseE = BasesToInheritFrom.end();
7216 BaseIt != BaseE; ++BaseIt) {
7217 const RecordType *Base = *BaseIt;
7218 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7219 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7220 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7221 CtorE = BaseDecl->ctor_end();
7222 CtorIt != CtorE; ++CtorIt) {
7223 // Find the using declaration for inheriting this base's constructors.
7224 DeclarationName Name =
7225 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7226 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7227 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7228 SourceLocation UsingLoc = UD ? UD->getLocation() :
7229 ClassDecl->getLocation();
7230
7231 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7232 // from the class X named in the using-declaration consists of actual
7233 // constructors and notional constructors that result from the
7234 // transformation of defaulted parameters as follows:
7235 // - all non-template default constructors of X, and
7236 // - for each non-template constructor of X that has at least one
7237 // parameter with a default argument, the set of constructors that
7238 // results from omitting any ellipsis parameter specification and
7239 // successively omitting parameters with a default argument from the
7240 // end of the parameter-type-list.
7241 CXXConstructorDecl *BaseCtor = *CtorIt;
7242 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7243 const FunctionProtoType *BaseCtorType =
7244 BaseCtor->getType()->getAs<FunctionProtoType>();
7245
7246 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7247 maxParams = BaseCtor->getNumParams();
7248 params <= maxParams; ++params) {
7249 // Skip default constructors. They're never inherited.
7250 if (params == 0)
7251 continue;
7252 // Skip copy and move constructors for the same reason.
7253 if (CanBeCopyOrMove && params == 1)
7254 continue;
7255
7256 // Build up a function type for this particular constructor.
7257 // FIXME: The working paper does not consider that the exception spec
7258 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007259 // source. This code doesn't yet, either. When it does, this code will
7260 // need to be delayed until after exception specifications and in-class
7261 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007262 const Type *NewCtorType;
7263 if (params == maxParams)
7264 NewCtorType = BaseCtorType;
7265 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007266 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007267 for (unsigned i = 0; i < params; ++i) {
7268 Args.push_back(BaseCtorType->getArgType(i));
7269 }
7270 FunctionProtoType::ExtProtoInfo ExtInfo =
7271 BaseCtorType->getExtProtoInfo();
7272 ExtInfo.Variadic = false;
7273 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7274 Args.data(), params, ExtInfo)
7275 .getTypePtr();
7276 }
7277 const Type *CanonicalNewCtorType =
7278 Context.getCanonicalType(NewCtorType);
7279
7280 // Now that we have the type, first check if the class already has a
7281 // constructor with this signature.
7282 if (ExistingConstructors.count(CanonicalNewCtorType))
7283 continue;
7284
7285 // Then we check if we have already declared an inherited constructor
7286 // with this signature.
7287 std::pair<ConstructorToSourceMap::iterator, bool> result =
7288 InheritedConstructors.insert(std::make_pair(
7289 CanonicalNewCtorType,
7290 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7291 if (!result.second) {
7292 // Already in the map. If it came from a different class, that's an
7293 // error. Not if it's from the same.
7294 CanQualType PreviousBase = result.first->second.first;
7295 if (CanonicalBase != PreviousBase) {
7296 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7297 const CXXConstructorDecl *PrevBaseCtor =
7298 PrevCtor->getInheritedConstructor();
7299 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7300
7301 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7302 Diag(BaseCtor->getLocation(),
7303 diag::note_using_decl_constructor_conflict_current_ctor);
7304 Diag(PrevBaseCtor->getLocation(),
7305 diag::note_using_decl_constructor_conflict_previous_ctor);
7306 Diag(PrevCtor->getLocation(),
7307 diag::note_using_decl_constructor_conflict_previous_using);
7308 }
7309 continue;
7310 }
7311
7312 // OK, we're there, now add the constructor.
7313 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007314 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007315 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7316 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007317 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7318 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007319 /*ImplicitlyDeclared=*/true,
7320 // FIXME: Due to a defect in the standard, we treat inherited
7321 // constructors as constexpr even if that makes them ill-formed.
7322 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007323 NewCtor->setAccess(BaseCtor->getAccess());
7324
7325 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007326 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007327 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007328 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7329 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007330 /*IdentifierInfo=*/0,
7331 BaseCtorType->getArgType(i),
7332 /*TInfo=*/0, SC_None,
7333 SC_None, /*DefaultArg=*/0));
7334 }
David Blaikie4278c652011-09-21 18:16:56 +00007335 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007336 NewCtor->setInheritedConstructor(BaseCtor);
7337
7338 PushOnScopeChains(NewCtor, S, false);
7339 ClassDecl->addDecl(NewCtor);
7340 result.first->second.second = NewCtor;
7341 }
7342 }
7343 }
7344}
7345
Sean Huntcb45a0f2011-05-12 22:46:25 +00007346Sema::ImplicitExceptionSpecification
7347Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007348 // C++ [except.spec]p14:
7349 // An implicitly declared special member function (Clause 12) shall have
7350 // an exception-specification.
7351 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007352 if (ClassDecl->isInvalidDecl())
7353 return ExceptSpec;
7354
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007355 // Direct base-class destructors.
7356 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7357 BEnd = ClassDecl->bases_end();
7358 B != BEnd; ++B) {
7359 if (B->isVirtual()) // Handled below.
7360 continue;
7361
7362 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7363 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007364 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007365 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007366
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007367 // Virtual base-class destructors.
7368 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7369 BEnd = ClassDecl->vbases_end();
7370 B != BEnd; ++B) {
7371 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7372 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007373 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007374 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007375
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007376 // Field destructors.
7377 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7378 FEnd = ClassDecl->field_end();
7379 F != FEnd; ++F) {
7380 if (const RecordType *RecordTy
7381 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7382 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007383 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007384 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007385
Sean Huntcb45a0f2011-05-12 22:46:25 +00007386 return ExceptSpec;
7387}
7388
7389CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7390 // C++ [class.dtor]p2:
7391 // If a class has no user-declared destructor, a destructor is
7392 // declared implicitly. An implicitly-declared destructor is an
7393 // inline public member of its class.
7394
7395 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007396 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007397 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7398
Douglas Gregor4923aa22010-07-02 20:37:36 +00007399 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007400 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007401
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007402 CanQualType ClassType
7403 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007404 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007405 DeclarationName Name
7406 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007407 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007408 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007409 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7410 /*isInline=*/true,
7411 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007412 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007413 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007414 Destructor->setImplicit();
7415 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007416
7417 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007418 ++ASTContext::NumImplicitDestructorsDeclared;
7419
7420 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007421 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007422 PushOnScopeChains(Destructor, S, false);
7423 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007424
7425 // This could be uniqued if it ever proves significant.
7426 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007427
7428 if (ShouldDeleteDestructor(Destructor))
7429 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007430
7431 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007432
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007433 return Destructor;
7434}
7435
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007436void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007437 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007438 assert((Destructor->isDefaulted() &&
7439 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007440 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007441 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007442 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007443
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007444 if (Destructor->isInvalidDecl())
7445 return;
7446
Douglas Gregor39957dc2010-05-01 15:04:51 +00007447 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007448
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007449 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007450 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7451 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007452
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007453 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007454 Diag(CurrentLocation, diag::note_member_synthesized_at)
7455 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7456
7457 Destructor->setInvalidDecl();
7458 return;
7459 }
7460
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007461 SourceLocation Loc = Destructor->getLocation();
7462 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007463 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007464 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007465 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007466
7467 if (ASTMutationListener *L = getASTMutationListener()) {
7468 L->CompletedImplicitDefinition(Destructor);
7469 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007470}
7471
Sebastian Redl0ee33912011-05-19 05:13:44 +00007472void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7473 CXXDestructorDecl *destructor) {
7474 // C++11 [class.dtor]p3:
7475 // A declaration of a destructor that does not have an exception-
7476 // specification is implicitly considered to have the same exception-
7477 // specification as an implicit declaration.
7478 const FunctionProtoType *dtorType = destructor->getType()->
7479 getAs<FunctionProtoType>();
7480 if (dtorType->hasExceptionSpec())
7481 return;
7482
7483 ImplicitExceptionSpecification exceptSpec =
7484 ComputeDefaultedDtorExceptionSpec(classDecl);
7485
Chandler Carruth3f224b22011-09-20 04:55:26 +00007486 // Replace the destructor's type, building off the existing one. Fortunately,
7487 // the only thing of interest in the destructor type is its extended info.
7488 // The return and arguments are fixed.
7489 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007490 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7491 epi.NumExceptions = exceptSpec.size();
7492 epi.Exceptions = exceptSpec.data();
7493 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7494
7495 destructor->setType(ty);
7496
7497 // FIXME: If the destructor has a body that could throw, and the newly created
7498 // spec doesn't allow exceptions, we should emit a warning, because this
7499 // change in behavior can break conforming C++03 programs at runtime.
7500 // However, we don't have a body yet, so it needs to be done somewhere else.
7501}
7502
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007503/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007504/// \c To.
7505///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007506/// This routine is used to copy/move the members of a class with an
7507/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007508/// copied are arrays, this routine builds for loops to copy them.
7509///
7510/// \param S The Sema object used for type-checking.
7511///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007512/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007513///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007514/// \param T The type of the expressions being copied/moved. Both expressions
7515/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007516///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007517/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007518///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007519/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007520///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007521/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007522/// Otherwise, it's a non-static member subobject.
7523///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007524/// \param Copying Whether we're copying or moving.
7525///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007526/// \param Depth Internal parameter recording the depth of the recursion.
7527///
7528/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007529static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007530BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007531 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007532 bool CopyingBaseSubobject, bool Copying,
7533 unsigned Depth = 0) {
7534 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007535 // Each subobject is assigned in the manner appropriate to its type:
7536 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007537 // - if the subobject is of class type, as if by a call to operator= with
7538 // the subobject as the object expression and the corresponding
7539 // subobject of x as a single function argument (as if by explicit
7540 // qualification; that is, ignoring any possible virtual overriding
7541 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007542 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7543 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7544
7545 // Look for operator=.
7546 DeclarationName Name
7547 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7548 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7549 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7550
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007551 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007552 LookupResult::Filter F = OpLookup.makeFilter();
7553 while (F.hasNext()) {
7554 NamedDecl *D = F.next();
7555 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007556 if (Copying ? Method->isCopyAssignmentOperator() :
7557 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007558 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007559
Douglas Gregor06a9f362010-05-01 20:49:11 +00007560 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007561 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007562 F.done();
7563
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007564 // Suppress the protected check (C++ [class.protected]) for each of the
7565 // assignment operators we found. This strange dance is required when
7566 // we're assigning via a base classes's copy-assignment operator. To
7567 // ensure that we're getting the right base class subobject (without
7568 // ambiguities), we need to cast "this" to that subobject type; to
7569 // ensure that we don't go through the virtual call mechanism, we need
7570 // to qualify the operator= name with the base class (see below). However,
7571 // this means that if the base class has a protected copy assignment
7572 // operator, the protected member access check will fail. So, we
7573 // rewrite "protected" access to "public" access in this case, since we
7574 // know by construction that we're calling from a derived class.
7575 if (CopyingBaseSubobject) {
7576 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7577 L != LEnd; ++L) {
7578 if (L.getAccess() == AS_protected)
7579 L.setAccess(AS_public);
7580 }
7581 }
7582
Douglas Gregor06a9f362010-05-01 20:49:11 +00007583 // Create the nested-name-specifier that will be used to qualify the
7584 // reference to operator=; this is required to suppress the virtual
7585 // call mechanism.
7586 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007587 SS.MakeTrivial(S.Context,
7588 NestedNameSpecifier::Create(S.Context, 0, false,
7589 T.getTypePtr()),
7590 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007591
7592 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007593 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007594 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007595 /*FirstQualifierInScope=*/0, OpLookup,
7596 /*TemplateArgs=*/0,
7597 /*SuppressQualifierCheck=*/true);
7598 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007599 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007600
7601 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007602
John McCall60d7b3a2010-08-24 06:29:42 +00007603 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007604 OpEqualRef.takeAs<Expr>(),
7605 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007606 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007607 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007608
7609 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007610 }
John McCallb0207482010-03-16 06:11:48 +00007611
Douglas Gregor06a9f362010-05-01 20:49:11 +00007612 // - if the subobject is of scalar type, the built-in assignment
7613 // operator is used.
7614 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7615 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007616 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007617 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007618 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007619
7620 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007621 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007622
7623 // - if the subobject is an array, each element is assigned, in the
7624 // manner appropriate to the element type;
7625
7626 // Construct a loop over the array bounds, e.g.,
7627 //
7628 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7629 //
7630 // that will copy each of the array elements.
7631 QualType SizeType = S.Context.getSizeType();
7632
7633 // Create the iteration variable.
7634 IdentifierInfo *IterationVarName = 0;
7635 {
7636 llvm::SmallString<8> Str;
7637 llvm::raw_svector_ostream OS(Str);
7638 OS << "__i" << Depth;
7639 IterationVarName = &S.Context.Idents.get(OS.str());
7640 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007641 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007642 IterationVarName, SizeType,
7643 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007644 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007645
7646 // Initialize the iteration variable to zero.
7647 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007648 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007649
7650 // Create a reference to the iteration variable; we'll use this several
7651 // times throughout.
7652 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007653 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007654 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007655 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7656 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7657
Douglas Gregor06a9f362010-05-01 20:49:11 +00007658 // Create the DeclStmt that holds the iteration variable.
7659 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7660
7661 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007662 llvm::APInt Upper
7663 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007664 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007665 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007666 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7667 BO_NE, S.Context.BoolTy,
7668 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669
7670 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007671 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007672 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7673 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007674
7675 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007676 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007677 IterationVarRefRVal,
7678 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007679 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007680 IterationVarRefRVal,
7681 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007682 if (!Copying) // Cast to rvalue
7683 From = CastForMoving(S, From);
7684
7685 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007686 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7687 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007688 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007689 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007690 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007691
7692 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007693 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007694 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007695 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007696 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007697}
7698
Sean Hunt30de05c2011-05-14 05:23:20 +00007699std::pair<Sema::ImplicitExceptionSpecification, bool>
7700Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7701 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007702 if (ClassDecl->isInvalidDecl())
7703 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7704
Douglas Gregord3c35902010-07-01 16:36:15 +00007705 // C++ [class.copy]p10:
7706 // If the class definition does not explicitly declare a copy
7707 // assignment operator, one is declared implicitly.
7708 // The implicitly-defined copy assignment operator for a class X
7709 // will have the form
7710 //
7711 // X& X::operator=(const X&)
7712 //
7713 // if
7714 bool HasConstCopyAssignment = true;
7715
7716 // -- each direct base class B of X has a copy assignment operator
7717 // whose parameter is of type const B&, const volatile B& or B,
7718 // and
7719 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7720 BaseEnd = ClassDecl->bases_end();
7721 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007722 // We'll handle this below
7723 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7724 continue;
7725
Douglas Gregord3c35902010-07-01 16:36:15 +00007726 assert(!Base->getType()->isDependentType() &&
7727 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007728 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7729 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7730 &HasConstCopyAssignment);
7731 }
7732
Richard Smithebaf0e62011-10-18 20:49:44 +00007733 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007734 if (LangOpts.CPlusPlus0x) {
7735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7736 BaseEnd = ClassDecl->vbases_end();
7737 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7738 assert(!Base->getType()->isDependentType() &&
7739 "Cannot generate implicit members for class with dependent bases.");
7740 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7741 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7742 &HasConstCopyAssignment);
7743 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007744 }
7745
7746 // -- for all the nonstatic data members of X that are of a class
7747 // type M (or array thereof), each such class type has a copy
7748 // assignment operator whose parameter is of type const M&,
7749 // const volatile M& or M.
7750 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7751 FieldEnd = ClassDecl->field_end();
7752 HasConstCopyAssignment && Field != FieldEnd;
7753 ++Field) {
7754 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007755 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7756 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7757 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007758 }
7759 }
7760
7761 // Otherwise, the implicitly declared copy assignment operator will
7762 // have the form
7763 //
7764 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007765
Douglas Gregorb87786f2010-07-01 17:48:08 +00007766 // C++ [except.spec]p14:
7767 // An implicitly declared special member function (Clause 12) shall have an
7768 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007769
7770 // It is unspecified whether or not an implicit copy assignment operator
7771 // attempts to deduplicate calls to assignment operators of virtual bases are
7772 // made. As such, this exception specification is effectively unspecified.
7773 // Based on a similar decision made for constness in C++0x, we're erring on
7774 // the side of assuming such calls to be made regardless of whether they
7775 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007776 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007777 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007778 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7779 BaseEnd = ClassDecl->bases_end();
7780 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007781 if (Base->isVirtual())
7782 continue;
7783
Douglas Gregora376d102010-07-02 21:50:04 +00007784 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007785 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007786 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7787 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007788 ExceptSpec.CalledDecl(CopyAssign);
7789 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007790
7791 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7792 BaseEnd = ClassDecl->vbases_end();
7793 Base != BaseEnd; ++Base) {
7794 CXXRecordDecl *BaseClassDecl
7795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7796 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7797 ArgQuals, false, 0))
7798 ExceptSpec.CalledDecl(CopyAssign);
7799 }
7800
Douglas Gregorb87786f2010-07-01 17:48:08 +00007801 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7802 FieldEnd = ClassDecl->field_end();
7803 Field != FieldEnd;
7804 ++Field) {
7805 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007806 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7807 if (CXXMethodDecl *CopyAssign =
7808 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7809 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007810 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007811 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007812
Sean Hunt30de05c2011-05-14 05:23:20 +00007813 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7814}
7815
7816CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7817 // Note: The following rules are largely analoguous to the copy
7818 // constructor rules. Note that virtual bases are not taken into account
7819 // for determining the argument type of the operator. Note also that
7820 // operators taking an object instead of a reference are allowed.
7821
7822 ImplicitExceptionSpecification Spec(Context);
7823 bool Const;
7824 llvm::tie(Spec, Const) =
7825 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7826
7827 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7828 QualType RetType = Context.getLValueReferenceType(ArgType);
7829 if (Const)
7830 ArgType = ArgType.withConst();
7831 ArgType = Context.getLValueReferenceType(ArgType);
7832
Douglas Gregord3c35902010-07-01 16:36:15 +00007833 // An implicitly-declared copy assignment operator is an inline public
7834 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007835 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007836 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007837 SourceLocation ClassLoc = ClassDecl->getLocation();
7838 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007839 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007840 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007841 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007842 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007843 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007844 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007845 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007846 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007847 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007848 CopyAssignment->setImplicit();
7849 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007850
7851 // Add the parameter to the operator.
7852 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007853 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007854 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007855 SC_None,
7856 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007857 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007858
Douglas Gregora376d102010-07-02 21:50:04 +00007859 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007860 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007861
Douglas Gregor23c94db2010-07-02 17:43:08 +00007862 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007863 PushOnScopeChains(CopyAssignment, S, false);
7864 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007865
Nico Weberafcc96a2012-01-23 03:19:29 +00007866 // C++0x [class.copy]p19:
7867 // .... If the class definition does not explicitly declare a copy
7868 // assignment operator, there is no user-declared move constructor, and
7869 // there is no user-declared move assignment operator, a copy assignment
7870 // operator is implicitly declared as defaulted.
7871 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007872 !getLangOptions().MicrosoftMode) ||
7873 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007874 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007875 CopyAssignment->setDeletedAsWritten();
7876
Douglas Gregord3c35902010-07-01 16:36:15 +00007877 AddOverriddenMethods(ClassDecl, CopyAssignment);
7878 return CopyAssignment;
7879}
7880
Douglas Gregor06a9f362010-05-01 20:49:11 +00007881void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7882 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007883 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007884 CopyAssignOperator->isOverloadedOperator() &&
7885 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007886 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007887 "DefineImplicitCopyAssignment called for wrong function");
7888
7889 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7890
7891 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7892 CopyAssignOperator->setInvalidDecl();
7893 return;
7894 }
7895
7896 CopyAssignOperator->setUsed();
7897
7898 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007899 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007900
7901 // C++0x [class.copy]p30:
7902 // The implicitly-defined or explicitly-defaulted copy assignment operator
7903 // for a non-union class X performs memberwise copy assignment of its
7904 // subobjects. The direct base classes of X are assigned first, in the
7905 // order of their declaration in the base-specifier-list, and then the
7906 // immediate non-static data members of X are assigned, in the order in
7907 // which they were declared in the class definition.
7908
7909 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007910 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007911
7912 // The parameter for the "other" object, which we are copying from.
7913 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7914 Qualifiers OtherQuals = Other->getType().getQualifiers();
7915 QualType OtherRefType = Other->getType();
7916 if (const LValueReferenceType *OtherRef
7917 = OtherRefType->getAs<LValueReferenceType>()) {
7918 OtherRefType = OtherRef->getPointeeType();
7919 OtherQuals = OtherRefType.getQualifiers();
7920 }
7921
7922 // Our location for everything implicitly-generated.
7923 SourceLocation Loc = CopyAssignOperator->getLocation();
7924
7925 // Construct a reference to the "other" object. We'll be using this
7926 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007927 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007928 assert(OtherRef && "Reference to parameter cannot fail!");
7929
7930 // Construct the "this" pointer. We'll be using this throughout the generated
7931 // ASTs.
7932 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7933 assert(This && "Reference to this cannot fail!");
7934
7935 // Assign base classes.
7936 bool Invalid = false;
7937 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7938 E = ClassDecl->bases_end(); Base != E; ++Base) {
7939 // Form the assignment:
7940 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7941 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007942 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007943 Invalid = true;
7944 continue;
7945 }
7946
John McCallf871d0c2010-08-07 06:22:56 +00007947 CXXCastPath BasePath;
7948 BasePath.push_back(Base);
7949
Douglas Gregor06a9f362010-05-01 20:49:11 +00007950 // Construct the "from" expression, which is an implicit cast to the
7951 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007952 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007953 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7954 CK_UncheckedDerivedToBase,
7955 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007956
7957 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007958 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007959
7960 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007961 To = ImpCastExprToType(To.take(),
7962 Context.getCVRQualifiedType(BaseType,
7963 CopyAssignOperator->getTypeQualifiers()),
7964 CK_UncheckedDerivedToBase,
7965 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007966
7967 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007968 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007969 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007970 /*CopyingBaseSubobject=*/true,
7971 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007972 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007973 Diag(CurrentLocation, diag::note_member_synthesized_at)
7974 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7975 CopyAssignOperator->setInvalidDecl();
7976 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007977 }
7978
7979 // Success! Record the copy.
7980 Statements.push_back(Copy.takeAs<Expr>());
7981 }
7982
7983 // \brief Reference to the __builtin_memcpy function.
7984 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007985 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007986 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007987
7988 // Assign non-static members.
7989 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7990 FieldEnd = ClassDecl->field_end();
7991 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007992 if (Field->isUnnamedBitfield())
7993 continue;
7994
Douglas Gregor06a9f362010-05-01 20:49:11 +00007995 // Check for members of reference type; we can't copy those.
7996 if (Field->getType()->isReferenceType()) {
7997 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7998 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7999 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008000 Diag(CurrentLocation, diag::note_member_synthesized_at)
8001 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008002 Invalid = true;
8003 continue;
8004 }
8005
8006 // Check for members of const-qualified, non-class type.
8007 QualType BaseType = Context.getBaseElementType(Field->getType());
8008 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8009 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8010 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8011 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008012 Diag(CurrentLocation, diag::note_member_synthesized_at)
8013 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008014 Invalid = true;
8015 continue;
8016 }
John McCallb77115d2011-06-17 00:18:42 +00008017
8018 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008019 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8020 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008021
8022 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008023 if (FieldType->isIncompleteArrayType()) {
8024 assert(ClassDecl->hasFlexibleArrayMember() &&
8025 "Incomplete array type is not valid");
8026 continue;
8027 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008028
8029 // Build references to the field in the object we're copying from and to.
8030 CXXScopeSpec SS; // Intentionally empty
8031 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8032 LookupMemberName);
8033 MemberLookup.addDecl(*Field);
8034 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008035 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008036 Loc, /*IsArrow=*/false,
8037 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008038 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008039 Loc, /*IsArrow=*/true,
8040 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008041 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8042 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8043
8044 // If the field should be copied with __builtin_memcpy rather than via
8045 // explicit assignments, do so. This optimization only applies for arrays
8046 // of scalars and arrays of class type with trivial copy-assignment
8047 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008048 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008049 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008050 // Compute the size of the memory buffer to be copied.
8051 QualType SizeType = Context.getSizeType();
8052 llvm::APInt Size(Context.getTypeSize(SizeType),
8053 Context.getTypeSizeInChars(BaseType).getQuantity());
8054 for (const ConstantArrayType *Array
8055 = Context.getAsConstantArrayType(FieldType);
8056 Array;
8057 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008058 llvm::APInt ArraySize
8059 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008060 Size *= ArraySize;
8061 }
8062
8063 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008064 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8065 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008066
8067 bool NeedsCollectableMemCpy =
8068 (BaseType->isRecordType() &&
8069 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8070
8071 if (NeedsCollectableMemCpy) {
8072 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008073 // Create a reference to the __builtin_objc_memmove_collectable function.
8074 LookupResult R(*this,
8075 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008076 Loc, LookupOrdinaryName);
8077 LookupName(R, TUScope, true);
8078
8079 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8080 if (!CollectableMemCpy) {
8081 // Something went horribly wrong earlier, and we will have
8082 // complained about it.
8083 Invalid = true;
8084 continue;
8085 }
8086
8087 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8088 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008089 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008090 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8091 }
8092 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008093 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008094 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008095 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8096 LookupOrdinaryName);
8097 LookupName(R, TUScope, true);
8098
8099 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8100 if (!BuiltinMemCpy) {
8101 // Something went horribly wrong earlier, and we will have complained
8102 // about it.
8103 Invalid = true;
8104 continue;
8105 }
8106
8107 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8108 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008109 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008110 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8111 }
8112
John McCallca0408f2010-08-23 06:44:23 +00008113 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008114 CallArgs.push_back(To.takeAs<Expr>());
8115 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008116 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008117 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008118 if (NeedsCollectableMemCpy)
8119 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008120 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008121 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008122 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008123 else
8124 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008125 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008126 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008127 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008128
Douglas Gregor06a9f362010-05-01 20:49:11 +00008129 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8130 Statements.push_back(Call.takeAs<Expr>());
8131 continue;
8132 }
8133
8134 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008135 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008136 To.get(), From.get(),
8137 /*CopyingBaseSubobject=*/false,
8138 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008139 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008140 Diag(CurrentLocation, diag::note_member_synthesized_at)
8141 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8142 CopyAssignOperator->setInvalidDecl();
8143 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008144 }
8145
8146 // Success! Record the copy.
8147 Statements.push_back(Copy.takeAs<Stmt>());
8148 }
8149
8150 if (!Invalid) {
8151 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008152 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008153
John McCall60d7b3a2010-08-24 06:29:42 +00008154 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008155 if (Return.isInvalid())
8156 Invalid = true;
8157 else {
8158 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008159
8160 if (Trap.hasErrorOccurred()) {
8161 Diag(CurrentLocation, diag::note_member_synthesized_at)
8162 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8163 Invalid = true;
8164 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008165 }
8166 }
8167
8168 if (Invalid) {
8169 CopyAssignOperator->setInvalidDecl();
8170 return;
8171 }
8172
John McCall60d7b3a2010-08-24 06:29:42 +00008173 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008174 /*isStmtExpr=*/false);
8175 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8176 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008177
8178 if (ASTMutationListener *L = getASTMutationListener()) {
8179 L->CompletedImplicitDefinition(CopyAssignOperator);
8180 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008181}
8182
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008183Sema::ImplicitExceptionSpecification
8184Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8185 ImplicitExceptionSpecification ExceptSpec(Context);
8186
8187 if (ClassDecl->isInvalidDecl())
8188 return ExceptSpec;
8189
8190 // C++0x [except.spec]p14:
8191 // An implicitly declared special member function (Clause 12) shall have an
8192 // exception-specification. [...]
8193
8194 // It is unspecified whether or not an implicit move assignment operator
8195 // attempts to deduplicate calls to assignment operators of virtual bases are
8196 // made. As such, this exception specification is effectively unspecified.
8197 // Based on a similar decision made for constness in C++0x, we're erring on
8198 // the side of assuming such calls to be made regardless of whether they
8199 // actually happen.
8200 // Note that a move constructor is not implicitly declared when there are
8201 // virtual bases, but it can still be user-declared and explicitly defaulted.
8202 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8203 BaseEnd = ClassDecl->bases_end();
8204 Base != BaseEnd; ++Base) {
8205 if (Base->isVirtual())
8206 continue;
8207
8208 CXXRecordDecl *BaseClassDecl
8209 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8210 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8211 false, 0))
8212 ExceptSpec.CalledDecl(MoveAssign);
8213 }
8214
8215 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8216 BaseEnd = ClassDecl->vbases_end();
8217 Base != BaseEnd; ++Base) {
8218 CXXRecordDecl *BaseClassDecl
8219 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8220 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8221 false, 0))
8222 ExceptSpec.CalledDecl(MoveAssign);
8223 }
8224
8225 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8226 FieldEnd = ClassDecl->field_end();
8227 Field != FieldEnd;
8228 ++Field) {
8229 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8230 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8231 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8232 false, 0))
8233 ExceptSpec.CalledDecl(MoveAssign);
8234 }
8235 }
8236
8237 return ExceptSpec;
8238}
8239
8240CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8241 // Note: The following rules are largely analoguous to the move
8242 // constructor rules.
8243
8244 ImplicitExceptionSpecification Spec(
8245 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8246
8247 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8248 QualType RetType = Context.getLValueReferenceType(ArgType);
8249 ArgType = Context.getRValueReferenceType(ArgType);
8250
8251 // An implicitly-declared move assignment operator is an inline public
8252 // member of its class.
8253 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8254 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8255 SourceLocation ClassLoc = ClassDecl->getLocation();
8256 DeclarationNameInfo NameInfo(Name, ClassLoc);
8257 CXXMethodDecl *MoveAssignment
8258 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8259 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8260 /*TInfo=*/0, /*isStatic=*/false,
8261 /*StorageClassAsWritten=*/SC_None,
8262 /*isInline=*/true,
8263 /*isConstexpr=*/false,
8264 SourceLocation());
8265 MoveAssignment->setAccess(AS_public);
8266 MoveAssignment->setDefaulted();
8267 MoveAssignment->setImplicit();
8268 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8269
8270 // Add the parameter to the operator.
8271 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8272 ClassLoc, ClassLoc, /*Id=*/0,
8273 ArgType, /*TInfo=*/0,
8274 SC_None,
8275 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008276 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008277
8278 // Note that we have added this copy-assignment operator.
8279 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8280
8281 // C++0x [class.copy]p9:
8282 // If the definition of a class X does not explicitly declare a move
8283 // assignment operator, one will be implicitly declared as defaulted if and
8284 // only if:
8285 // [...]
8286 // - the move assignment operator would not be implicitly defined as
8287 // deleted.
8288 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8289 // Cache this result so that we don't try to generate this over and over
8290 // on every lookup, leaking memory and wasting time.
8291 ClassDecl->setFailedImplicitMoveAssignment();
8292 return 0;
8293 }
8294
8295 if (Scope *S = getScopeForContext(ClassDecl))
8296 PushOnScopeChains(MoveAssignment, S, false);
8297 ClassDecl->addDecl(MoveAssignment);
8298
8299 AddOverriddenMethods(ClassDecl, MoveAssignment);
8300 return MoveAssignment;
8301}
8302
8303void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8304 CXXMethodDecl *MoveAssignOperator) {
8305 assert((MoveAssignOperator->isDefaulted() &&
8306 MoveAssignOperator->isOverloadedOperator() &&
8307 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8308 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8309 "DefineImplicitMoveAssignment called for wrong function");
8310
8311 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8312
8313 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8314 MoveAssignOperator->setInvalidDecl();
8315 return;
8316 }
8317
8318 MoveAssignOperator->setUsed();
8319
8320 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8321 DiagnosticErrorTrap Trap(Diags);
8322
8323 // C++0x [class.copy]p28:
8324 // The implicitly-defined or move assignment operator for a non-union class
8325 // X performs memberwise move assignment of its subobjects. The direct base
8326 // classes of X are assigned first, in the order of their declaration in the
8327 // base-specifier-list, and then the immediate non-static data members of X
8328 // are assigned, in the order in which they were declared in the class
8329 // definition.
8330
8331 // The statements that form the synthesized function body.
8332 ASTOwningVector<Stmt*> Statements(*this);
8333
8334 // The parameter for the "other" object, which we are move from.
8335 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8336 QualType OtherRefType = Other->getType()->
8337 getAs<RValueReferenceType>()->getPointeeType();
8338 assert(OtherRefType.getQualifiers() == 0 &&
8339 "Bad argument type of defaulted move assignment");
8340
8341 // Our location for everything implicitly-generated.
8342 SourceLocation Loc = MoveAssignOperator->getLocation();
8343
8344 // Construct a reference to the "other" object. We'll be using this
8345 // throughout the generated ASTs.
8346 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8347 assert(OtherRef && "Reference to parameter cannot fail!");
8348 // Cast to rvalue.
8349 OtherRef = CastForMoving(*this, OtherRef);
8350
8351 // Construct the "this" pointer. We'll be using this throughout the generated
8352 // ASTs.
8353 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8354 assert(This && "Reference to this cannot fail!");
8355
8356 // Assign base classes.
8357 bool Invalid = false;
8358 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8359 E = ClassDecl->bases_end(); Base != E; ++Base) {
8360 // Form the assignment:
8361 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8362 QualType BaseType = Base->getType().getUnqualifiedType();
8363 if (!BaseType->isRecordType()) {
8364 Invalid = true;
8365 continue;
8366 }
8367
8368 CXXCastPath BasePath;
8369 BasePath.push_back(Base);
8370
8371 // Construct the "from" expression, which is an implicit cast to the
8372 // appropriately-qualified base type.
8373 Expr *From = OtherRef;
8374 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008375 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008376
8377 // Dereference "this".
8378 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8379
8380 // Implicitly cast "this" to the appropriately-qualified base type.
8381 To = ImpCastExprToType(To.take(),
8382 Context.getCVRQualifiedType(BaseType,
8383 MoveAssignOperator->getTypeQualifiers()),
8384 CK_UncheckedDerivedToBase,
8385 VK_LValue, &BasePath);
8386
8387 // Build the move.
8388 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8389 To.get(), From,
8390 /*CopyingBaseSubobject=*/true,
8391 /*Copying=*/false);
8392 if (Move.isInvalid()) {
8393 Diag(CurrentLocation, diag::note_member_synthesized_at)
8394 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8395 MoveAssignOperator->setInvalidDecl();
8396 return;
8397 }
8398
8399 // Success! Record the move.
8400 Statements.push_back(Move.takeAs<Expr>());
8401 }
8402
8403 // \brief Reference to the __builtin_memcpy function.
8404 Expr *BuiltinMemCpyRef = 0;
8405 // \brief Reference to the __builtin_objc_memmove_collectable function.
8406 Expr *CollectableMemCpyRef = 0;
8407
8408 // Assign non-static members.
8409 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8410 FieldEnd = ClassDecl->field_end();
8411 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008412 if (Field->isUnnamedBitfield())
8413 continue;
8414
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008415 // Check for members of reference type; we can't move those.
8416 if (Field->getType()->isReferenceType()) {
8417 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8418 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8419 Diag(Field->getLocation(), diag::note_declared_at);
8420 Diag(CurrentLocation, diag::note_member_synthesized_at)
8421 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8422 Invalid = true;
8423 continue;
8424 }
8425
8426 // Check for members of const-qualified, non-class type.
8427 QualType BaseType = Context.getBaseElementType(Field->getType());
8428 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8429 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8430 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8431 Diag(Field->getLocation(), diag::note_declared_at);
8432 Diag(CurrentLocation, diag::note_member_synthesized_at)
8433 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8434 Invalid = true;
8435 continue;
8436 }
8437
8438 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008439 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8440 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008441
8442 QualType FieldType = Field->getType().getNonReferenceType();
8443 if (FieldType->isIncompleteArrayType()) {
8444 assert(ClassDecl->hasFlexibleArrayMember() &&
8445 "Incomplete array type is not valid");
8446 continue;
8447 }
8448
8449 // Build references to the field in the object we're copying from and to.
8450 CXXScopeSpec SS; // Intentionally empty
8451 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8452 LookupMemberName);
8453 MemberLookup.addDecl(*Field);
8454 MemberLookup.resolveKind();
8455 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8456 Loc, /*IsArrow=*/false,
8457 SS, 0, MemberLookup, 0);
8458 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8459 Loc, /*IsArrow=*/true,
8460 SS, 0, MemberLookup, 0);
8461 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8462 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8463
8464 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8465 "Member reference with rvalue base must be rvalue except for reference "
8466 "members, which aren't allowed for move assignment.");
8467
8468 // If the field should be copied with __builtin_memcpy rather than via
8469 // explicit assignments, do so. This optimization only applies for arrays
8470 // of scalars and arrays of class type with trivial move-assignment
8471 // operators.
8472 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8473 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8474 // Compute the size of the memory buffer to be copied.
8475 QualType SizeType = Context.getSizeType();
8476 llvm::APInt Size(Context.getTypeSize(SizeType),
8477 Context.getTypeSizeInChars(BaseType).getQuantity());
8478 for (const ConstantArrayType *Array
8479 = Context.getAsConstantArrayType(FieldType);
8480 Array;
8481 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8482 llvm::APInt ArraySize
8483 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8484 Size *= ArraySize;
8485 }
8486
Douglas Gregor45d3d712011-09-01 02:09:07 +00008487 // Take the address of the field references for "from" and "to". We
8488 // directly construct UnaryOperators here because semantic analysis
8489 // does not permit us to take the address of an xvalue.
8490 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8491 Context.getPointerType(From.get()->getType()),
8492 VK_RValue, OK_Ordinary, Loc);
8493 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8494 Context.getPointerType(To.get()->getType()),
8495 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008496
8497 bool NeedsCollectableMemCpy =
8498 (BaseType->isRecordType() &&
8499 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8500
8501 if (NeedsCollectableMemCpy) {
8502 if (!CollectableMemCpyRef) {
8503 // Create a reference to the __builtin_objc_memmove_collectable function.
8504 LookupResult R(*this,
8505 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8506 Loc, LookupOrdinaryName);
8507 LookupName(R, TUScope, true);
8508
8509 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8510 if (!CollectableMemCpy) {
8511 // Something went horribly wrong earlier, and we will have
8512 // complained about it.
8513 Invalid = true;
8514 continue;
8515 }
8516
8517 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8518 CollectableMemCpy->getType(),
8519 VK_LValue, Loc, 0).take();
8520 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8521 }
8522 }
8523 // Create a reference to the __builtin_memcpy builtin function.
8524 else if (!BuiltinMemCpyRef) {
8525 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8526 LookupOrdinaryName);
8527 LookupName(R, TUScope, true);
8528
8529 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8530 if (!BuiltinMemCpy) {
8531 // Something went horribly wrong earlier, and we will have complained
8532 // about it.
8533 Invalid = true;
8534 continue;
8535 }
8536
8537 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8538 BuiltinMemCpy->getType(),
8539 VK_LValue, Loc, 0).take();
8540 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8541 }
8542
8543 ASTOwningVector<Expr*> CallArgs(*this);
8544 CallArgs.push_back(To.takeAs<Expr>());
8545 CallArgs.push_back(From.takeAs<Expr>());
8546 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8547 ExprResult Call = ExprError();
8548 if (NeedsCollectableMemCpy)
8549 Call = ActOnCallExpr(/*Scope=*/0,
8550 CollectableMemCpyRef,
8551 Loc, move_arg(CallArgs),
8552 Loc);
8553 else
8554 Call = ActOnCallExpr(/*Scope=*/0,
8555 BuiltinMemCpyRef,
8556 Loc, move_arg(CallArgs),
8557 Loc);
8558
8559 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8560 Statements.push_back(Call.takeAs<Expr>());
8561 continue;
8562 }
8563
8564 // Build the move of this field.
8565 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8566 To.get(), From.get(),
8567 /*CopyingBaseSubobject=*/false,
8568 /*Copying=*/false);
8569 if (Move.isInvalid()) {
8570 Diag(CurrentLocation, diag::note_member_synthesized_at)
8571 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8572 MoveAssignOperator->setInvalidDecl();
8573 return;
8574 }
8575
8576 // Success! Record the copy.
8577 Statements.push_back(Move.takeAs<Stmt>());
8578 }
8579
8580 if (!Invalid) {
8581 // Add a "return *this;"
8582 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8583
8584 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8585 if (Return.isInvalid())
8586 Invalid = true;
8587 else {
8588 Statements.push_back(Return.takeAs<Stmt>());
8589
8590 if (Trap.hasErrorOccurred()) {
8591 Diag(CurrentLocation, diag::note_member_synthesized_at)
8592 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8593 Invalid = true;
8594 }
8595 }
8596 }
8597
8598 if (Invalid) {
8599 MoveAssignOperator->setInvalidDecl();
8600 return;
8601 }
8602
8603 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8604 /*isStmtExpr=*/false);
8605 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8606 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8607
8608 if (ASTMutationListener *L = getASTMutationListener()) {
8609 L->CompletedImplicitDefinition(MoveAssignOperator);
8610 }
8611}
8612
Sean Hunt49634cf2011-05-13 06:10:58 +00008613std::pair<Sema::ImplicitExceptionSpecification, bool>
8614Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008615 if (ClassDecl->isInvalidDecl())
8616 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8617
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008618 // C++ [class.copy]p5:
8619 // The implicitly-declared copy constructor for a class X will
8620 // have the form
8621 //
8622 // X::X(const X&)
8623 //
8624 // if
Sean Huntc530d172011-06-10 04:44:37 +00008625 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008626 bool HasConstCopyConstructor = true;
8627
8628 // -- each direct or virtual base class B of X has a copy
8629 // constructor whose first parameter is of type const B& or
8630 // const volatile B&, and
8631 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8632 BaseEnd = ClassDecl->bases_end();
8633 HasConstCopyConstructor && Base != BaseEnd;
8634 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008635 // Virtual bases are handled below.
8636 if (Base->isVirtual())
8637 continue;
8638
Douglas Gregor22584312010-07-02 23:41:54 +00008639 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008640 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008641 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8642 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008643 }
8644
8645 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8646 BaseEnd = ClassDecl->vbases_end();
8647 HasConstCopyConstructor && Base != BaseEnd;
8648 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008649 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008650 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008651 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8652 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008653 }
8654
8655 // -- for all the nonstatic data members of X that are of a
8656 // class type M (or array thereof), each such class type
8657 // has a copy constructor whose first parameter is of type
8658 // const M& or const volatile M&.
8659 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8660 FieldEnd = ClassDecl->field_end();
8661 HasConstCopyConstructor && Field != FieldEnd;
8662 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008663 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008664 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008665 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8666 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008667 }
8668 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008669 // Otherwise, the implicitly declared copy constructor will have
8670 // the form
8671 //
8672 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008673
Douglas Gregor0d405db2010-07-01 20:59:04 +00008674 // C++ [except.spec]p14:
8675 // An implicitly declared special member function (Clause 12) shall have an
8676 // exception-specification. [...]
8677 ImplicitExceptionSpecification ExceptSpec(Context);
8678 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8679 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8680 BaseEnd = ClassDecl->bases_end();
8681 Base != BaseEnd;
8682 ++Base) {
8683 // Virtual bases are handled below.
8684 if (Base->isVirtual())
8685 continue;
8686
Douglas Gregor22584312010-07-02 23:41:54 +00008687 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008688 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008689 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008690 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008691 ExceptSpec.CalledDecl(CopyConstructor);
8692 }
8693 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8694 BaseEnd = ClassDecl->vbases_end();
8695 Base != BaseEnd;
8696 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008697 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008698 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008699 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008700 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008701 ExceptSpec.CalledDecl(CopyConstructor);
8702 }
8703 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8704 FieldEnd = ClassDecl->field_end();
8705 Field != FieldEnd;
8706 ++Field) {
8707 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008708 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8709 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008710 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008711 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008712 }
8713 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008714
Sean Hunt49634cf2011-05-13 06:10:58 +00008715 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8716}
8717
8718CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8719 CXXRecordDecl *ClassDecl) {
8720 // C++ [class.copy]p4:
8721 // If the class definition does not explicitly declare a copy
8722 // constructor, one is declared implicitly.
8723
8724 ImplicitExceptionSpecification Spec(Context);
8725 bool Const;
8726 llvm::tie(Spec, Const) =
8727 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8728
8729 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8730 QualType ArgType = ClassType;
8731 if (Const)
8732 ArgType = ArgType.withConst();
8733 ArgType = Context.getLValueReferenceType(ArgType);
8734
8735 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8736
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008737 DeclarationName Name
8738 = Context.DeclarationNames.getCXXConstructorName(
8739 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008740 SourceLocation ClassLoc = ClassDecl->getLocation();
8741 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008742
8743 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008744 // member of its class.
8745 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8746 Context, ClassDecl, ClassLoc, NameInfo,
8747 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8748 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8749 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8750 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008751 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008752 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008753 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008754
Douglas Gregor22584312010-07-02 23:41:54 +00008755 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008756 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8757
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008758 // Add the parameter to the constructor.
8759 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008760 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008761 /*IdentifierInfo=*/0,
8762 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008763 SC_None,
8764 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008765 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008766
Douglas Gregor23c94db2010-07-02 17:43:08 +00008767 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008768 PushOnScopeChains(CopyConstructor, S, false);
8769 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008770
Nico Weberafcc96a2012-01-23 03:19:29 +00008771 // C++11 [class.copy]p8:
8772 // ... If the class definition does not explicitly declare a copy
8773 // constructor, there is no user-declared move constructor, and there is no
8774 // user-declared move assignment operator, a copy constructor is implicitly
8775 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008776 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008777 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008778 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008779 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008780 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008781
8782 return CopyConstructor;
8783}
8784
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008785void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008786 CXXConstructorDecl *CopyConstructor) {
8787 assert((CopyConstructor->isDefaulted() &&
8788 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008789 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008790 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008791
Anders Carlsson63010a72010-04-23 16:24:12 +00008792 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008793 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008794
Douglas Gregor39957dc2010-05-01 15:04:51 +00008795 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008796 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008797
Sean Huntcbb67482011-01-08 20:30:50 +00008798 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008799 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008800 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008801 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008802 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008803 } else {
8804 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8805 CopyConstructor->getLocation(),
8806 MultiStmtArg(*this, 0, 0),
8807 /*isStmtExpr=*/false)
8808 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008809 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008810 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008811
8812 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008813 if (ASTMutationListener *L = getASTMutationListener()) {
8814 L->CompletedImplicitDefinition(CopyConstructor);
8815 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008816}
8817
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008818Sema::ImplicitExceptionSpecification
8819Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8820 // C++ [except.spec]p14:
8821 // An implicitly declared special member function (Clause 12) shall have an
8822 // exception-specification. [...]
8823 ImplicitExceptionSpecification ExceptSpec(Context);
8824 if (ClassDecl->isInvalidDecl())
8825 return ExceptSpec;
8826
8827 // Direct base-class constructors.
8828 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8829 BEnd = ClassDecl->bases_end();
8830 B != BEnd; ++B) {
8831 if (B->isVirtual()) // Handled below.
8832 continue;
8833
8834 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8835 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8836 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8837 // If this is a deleted function, add it anyway. This might be conformant
8838 // with the standard. This might not. I'm not sure. It might not matter.
8839 if (Constructor)
8840 ExceptSpec.CalledDecl(Constructor);
8841 }
8842 }
8843
8844 // Virtual base-class constructors.
8845 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8846 BEnd = ClassDecl->vbases_end();
8847 B != BEnd; ++B) {
8848 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8849 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8850 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8851 // If this is a deleted function, add it anyway. This might be conformant
8852 // with the standard. This might not. I'm not sure. It might not matter.
8853 if (Constructor)
8854 ExceptSpec.CalledDecl(Constructor);
8855 }
8856 }
8857
8858 // Field constructors.
8859 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8860 FEnd = ClassDecl->field_end();
8861 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008862 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008863 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8864 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8865 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8866 // If this is a deleted function, add it anyway. This might be conformant
8867 // with the standard. This might not. I'm not sure. It might not matter.
8868 // In particular, the problem is that this function never gets called. It
8869 // might just be ill-formed because this function attempts to refer to
8870 // a deleted function here.
8871 if (Constructor)
8872 ExceptSpec.CalledDecl(Constructor);
8873 }
8874 }
8875
8876 return ExceptSpec;
8877}
8878
8879CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8880 CXXRecordDecl *ClassDecl) {
8881 ImplicitExceptionSpecification Spec(
8882 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8883
8884 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8885 QualType ArgType = Context.getRValueReferenceType(ClassType);
8886
8887 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8888
8889 DeclarationName Name
8890 = Context.DeclarationNames.getCXXConstructorName(
8891 Context.getCanonicalType(ClassType));
8892 SourceLocation ClassLoc = ClassDecl->getLocation();
8893 DeclarationNameInfo NameInfo(Name, ClassLoc);
8894
8895 // C++0x [class.copy]p11:
8896 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008897 // member of its class.
8898 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8899 Context, ClassDecl, ClassLoc, NameInfo,
8900 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8901 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8902 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8903 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008904 MoveConstructor->setAccess(AS_public);
8905 MoveConstructor->setDefaulted();
8906 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008907
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008908 // Add the parameter to the constructor.
8909 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8910 ClassLoc, ClassLoc,
8911 /*IdentifierInfo=*/0,
8912 ArgType, /*TInfo=*/0,
8913 SC_None,
8914 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008915 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008916
8917 // C++0x [class.copy]p9:
8918 // If the definition of a class X does not explicitly declare a move
8919 // constructor, one will be implicitly declared as defaulted if and only if:
8920 // [...]
8921 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008922 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008923 // Cache this result so that we don't try to generate this over and over
8924 // on every lookup, leaking memory and wasting time.
8925 ClassDecl->setFailedImplicitMoveConstructor();
8926 return 0;
8927 }
8928
8929 // Note that we have declared this constructor.
8930 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8931
8932 if (Scope *S = getScopeForContext(ClassDecl))
8933 PushOnScopeChains(MoveConstructor, S, false);
8934 ClassDecl->addDecl(MoveConstructor);
8935
8936 return MoveConstructor;
8937}
8938
8939void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8940 CXXConstructorDecl *MoveConstructor) {
8941 assert((MoveConstructor->isDefaulted() &&
8942 MoveConstructor->isMoveConstructor() &&
8943 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8944 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8945
8946 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8947 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8948
8949 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8950 DiagnosticErrorTrap Trap(Diags);
8951
8952 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8953 Trap.hasErrorOccurred()) {
8954 Diag(CurrentLocation, diag::note_member_synthesized_at)
8955 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8956 MoveConstructor->setInvalidDecl();
8957 } else {
8958 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8959 MoveConstructor->getLocation(),
8960 MultiStmtArg(*this, 0, 0),
8961 /*isStmtExpr=*/false)
8962 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008963 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008964 }
8965
8966 MoveConstructor->setUsed();
8967
8968 if (ASTMutationListener *L = getASTMutationListener()) {
8969 L->CompletedImplicitDefinition(MoveConstructor);
8970 }
8971}
8972
John McCall60d7b3a2010-08-24 06:29:42 +00008973ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008974Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008975 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008976 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008977 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008978 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008979 unsigned ConstructKind,
8980 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008981 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008982
Douglas Gregor2f599792010-04-02 18:24:57 +00008983 // C++0x [class.copy]p34:
8984 // When certain criteria are met, an implementation is allowed to
8985 // omit the copy/move construction of a class object, even if the
8986 // copy/move constructor and/or destructor for the object have
8987 // side effects. [...]
8988 // - when a temporary class object that has not been bound to a
8989 // reference (12.2) would be copied/moved to a class object
8990 // with the same cv-unqualified type, the copy/move operation
8991 // can be omitted by constructing the temporary object
8992 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008993 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008994 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008995 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008996 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008997 }
Mike Stump1eb44332009-09-09 15:08:12 +00008998
8999 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009000 Elidable, move(ExprArgs), HadMultipleCandidates,
9001 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009002}
9003
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009004/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9005/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009006ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009007Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9008 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009009 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009010 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009011 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009012 unsigned ConstructKind,
9013 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009014 unsigned NumExprs = ExprArgs.size();
9015 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009016
Nick Lewycky909a70d2011-03-25 01:44:32 +00009017 for (specific_attr_iterator<NonNullAttr>
9018 i = Constructor->specific_attr_begin<NonNullAttr>(),
9019 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9020 const NonNullAttr *NonNull = *i;
9021 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9022 }
9023
Douglas Gregor7edfb692009-11-23 12:27:39 +00009024 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009025 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009026 Constructor, Elidable, Exprs, NumExprs,
9027 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009028 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9029 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009030}
9031
Mike Stump1eb44332009-09-09 15:08:12 +00009032bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009033 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009034 MultiExprArg Exprs,
9035 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009036 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009037 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009038 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009039 move(Exprs), HadMultipleCandidates, false,
9040 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009041 if (TempResult.isInvalid())
9042 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009043
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009044 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009045 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009046 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009047 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009048 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009049
Anders Carlssonfe2de492009-08-25 05:18:00 +00009050 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009051}
9052
John McCall68c6c9a2010-02-02 09:10:11 +00009053void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009054 if (VD->isInvalidDecl()) return;
9055
John McCall68c6c9a2010-02-02 09:10:11 +00009056 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009057 if (ClassDecl->isInvalidDecl()) return;
9058 if (ClassDecl->hasTrivialDestructor()) return;
9059 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009060
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009061 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9062 MarkDeclarationReferenced(VD->getLocation(), Destructor);
9063 CheckDestructorAccess(VD->getLocation(), Destructor,
9064 PDiag(diag::err_access_dtor_var)
9065 << VD->getDeclName()
9066 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009067
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009068 if (!VD->hasGlobalStorage()) return;
9069
9070 // Emit warning for non-trivial dtor in global scope (a real global,
9071 // class-static, function-static).
9072 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9073
9074 // TODO: this should be re-enabled for static locals by !CXAAtExit
9075 if (!VD->isStaticLocal())
9076 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009077}
9078
Mike Stump1eb44332009-09-09 15:08:12 +00009079/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009080/// ActOnDeclarator, when a C++ direct initializer is present.
9081/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009082void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009083 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009084 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009085 SourceLocation RParenLoc,
9086 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009087 // If there is no declaration, there was an error parsing it. Just ignore
9088 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009089 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009090 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009091
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009092 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9093 if (!VDecl) {
9094 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9095 RealDecl->setInvalidDecl();
9096 return;
9097 }
9098
Eli Friedman6aeaa602012-01-05 22:34:08 +00009099 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00009100 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00009101 if (Exprs.size() == 0) {
9102 // It isn't possible to write this directly, but it is possible to
9103 // end up in this situation with "auto x(some_pack...);"
9104 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9105 << VDecl->getDeclName() << VDecl->getType()
9106 << VDecl->getSourceRange();
9107 RealDecl->setInvalidDecl();
9108 return;
9109 }
9110
Richard Smith34b41d92011-02-20 03:19:35 +00009111 if (Exprs.size() > 1) {
9112 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9113 diag::err_auto_var_init_multiple_expressions)
9114 << VDecl->getDeclName() << VDecl->getType()
9115 << VDecl->getSourceRange();
9116 RealDecl->setInvalidDecl();
9117 return;
9118 }
9119
9120 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009121 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00009122 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9123 DAR_Failed)
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00009124 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smitha085da82011-03-17 16:11:59 +00009125 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009126 RealDecl->setInvalidDecl();
9127 return;
9128 }
Richard Smitha085da82011-03-17 16:11:59 +00009129 VDecl->setTypeSourceInfo(DeducedType);
9130 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009131
John McCallf85e1932011-06-15 23:02:42 +00009132 // In ARC, infer lifetime.
9133 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9134 VDecl->setInvalidDecl();
9135
Richard Smith34b41d92011-02-20 03:19:35 +00009136 // If this is a redeclaration, check that the type we just deduced matches
9137 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00009138 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00009139 MergeVarDeclTypes(VDecl, Old);
9140 }
9141
Douglas Gregor83ddad32009-08-26 21:14:46 +00009142 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009143 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009144 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9145 //
9146 // Clients that want to distinguish between the two forms, can check for
9147 // direct initializer using VarDecl::hasCXXDirectInitializer().
9148 // A major benefit is that clients that don't particularly care about which
9149 // exactly form was it (like the CodeGen) can handle both cases without
9150 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009151
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009152 // C++ 8.5p11:
9153 // The form of initialization (using parentheses or '=') is generally
9154 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009155 // class type.
9156
Douglas Gregor4dffad62010-02-11 22:55:30 +00009157 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009158 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009159 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009160 diag::err_typecheck_decl_incomplete_type)) {
9161 VDecl->setInvalidDecl();
9162 return;
9163 }
9164
Douglas Gregor90f93822009-12-22 22:17:25 +00009165 // The variable can not have an abstract class type.
9166 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9167 diag::err_abstract_type_in_decl,
9168 AbstractVariableType))
9169 VDecl->setInvalidDecl();
9170
Sebastian Redl31310a22010-02-01 20:16:42 +00009171 const VarDecl *Def;
9172 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009173 Diag(VDecl->getLocation(), diag::err_redefinition)
9174 << VDecl->getDeclName();
9175 Diag(Def->getLocation(), diag::note_previous_definition);
9176 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009177 return;
9178 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009179
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009180 // C++ [class.static.data]p4
9181 // If a static data member is of const integral or const
9182 // enumeration type, its declaration in the class definition can
9183 // specify a constant-initializer which shall be an integral
9184 // constant expression (5.19). In that case, the member can appear
9185 // in integral constant expressions. The member shall still be
9186 // defined in a namespace scope if it is used in the program and the
9187 // namespace scope definition shall not contain an initializer.
9188 //
9189 // We already performed a redefinition check above, but for static
9190 // data members we also need to check whether there was an in-class
9191 // declaration with an initializer.
9192 const VarDecl* PrevInit = 0;
9193 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9194 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9195 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9196 return;
9197 }
9198
Douglas Gregora31040f2010-12-16 01:31:22 +00009199 bool IsDependent = false;
9200 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9201 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9202 VDecl->setInvalidDecl();
9203 return;
9204 }
9205
9206 if (Exprs.get()[I]->isTypeDependent())
9207 IsDependent = true;
9208 }
9209
Douglas Gregor4dffad62010-02-11 22:55:30 +00009210 // If either the declaration has a dependent type or if any of the
9211 // expressions is type-dependent, we represent the initialization
9212 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009213 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009214 // Let clients know that initialization was done with a direct initializer.
9215 VDecl->setCXXDirectInitializer(true);
9216
9217 // Store the initialization expressions as a ParenListExpr.
9218 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009219 VDecl->setInit(new (Context) ParenListExpr(
9220 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9221 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009222 return;
9223 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009224
9225 // Capture the variable that is being initialized and the style of
9226 // initialization.
9227 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9228
9229 // FIXME: Poor source location information.
9230 InitializationKind Kind
9231 = InitializationKind::CreateDirect(VDecl->getLocation(),
9232 LParenLoc, RParenLoc);
9233
Douglas Gregord24c3062011-10-10 16:05:18 +00009234 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009235 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009236 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009237 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009238 if (Result.isInvalid()) {
9239 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009240 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009241 } else if (T != VDecl->getType()) {
9242 VDecl->setType(T);
9243 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009244 }
John McCallb4eb64d2010-10-08 02:01:28 +00009245
Douglas Gregord24c3062011-10-10 16:05:18 +00009246
Richard Smithc6d990a2011-09-29 19:11:37 +00009247 Expr *Init = Result.get();
9248 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009249
9250 Init = MaybeCreateExprWithCleanups(Init);
9251 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009252 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009253
John McCall2998d6b2011-01-19 11:48:09 +00009254 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009255}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009256
Douglas Gregor39da0b82009-09-09 23:08:42 +00009257/// \brief Given a constructor and the set of arguments provided for the
9258/// constructor, convert the arguments and add any required default arguments
9259/// to form a proper call to this constructor.
9260///
9261/// \returns true if an error occurred, false otherwise.
9262bool
9263Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9264 MultiExprArg ArgsPtr,
9265 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009266 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009267 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9268 unsigned NumArgs = ArgsPtr.size();
9269 Expr **Args = (Expr **)ArgsPtr.get();
9270
9271 const FunctionProtoType *Proto
9272 = Constructor->getType()->getAs<FunctionProtoType>();
9273 assert(Proto && "Constructor without a prototype?");
9274 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009275
9276 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009277 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009278 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009279 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009280 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009281
9282 VariadicCallType CallType =
9283 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009284 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009285 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9286 Proto, 0, Args, NumArgs, AllArgs,
9287 CallType);
9288 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9289 ConvertedArgs.push_back(AllArgs[i]);
9290 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009291}
9292
Anders Carlsson20d45d22009-12-12 00:32:00 +00009293static inline bool
9294CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9295 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009296 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009297 if (isa<NamespaceDecl>(DC)) {
9298 return SemaRef.Diag(FnDecl->getLocation(),
9299 diag::err_operator_new_delete_declared_in_namespace)
9300 << FnDecl->getDeclName();
9301 }
9302
9303 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009304 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009305 return SemaRef.Diag(FnDecl->getLocation(),
9306 diag::err_operator_new_delete_declared_static)
9307 << FnDecl->getDeclName();
9308 }
9309
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009310 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009311}
9312
Anders Carlsson156c78e2009-12-13 17:53:43 +00009313static inline bool
9314CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9315 CanQualType ExpectedResultType,
9316 CanQualType ExpectedFirstParamType,
9317 unsigned DependentParamTypeDiag,
9318 unsigned InvalidParamTypeDiag) {
9319 QualType ResultType =
9320 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9321
9322 // Check that the result type is not dependent.
9323 if (ResultType->isDependentType())
9324 return SemaRef.Diag(FnDecl->getLocation(),
9325 diag::err_operator_new_delete_dependent_result_type)
9326 << FnDecl->getDeclName() << ExpectedResultType;
9327
9328 // Check that the result type is what we expect.
9329 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9330 return SemaRef.Diag(FnDecl->getLocation(),
9331 diag::err_operator_new_delete_invalid_result_type)
9332 << FnDecl->getDeclName() << ExpectedResultType;
9333
9334 // A function template must have at least 2 parameters.
9335 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9336 return SemaRef.Diag(FnDecl->getLocation(),
9337 diag::err_operator_new_delete_template_too_few_parameters)
9338 << FnDecl->getDeclName();
9339
9340 // The function decl must have at least 1 parameter.
9341 if (FnDecl->getNumParams() == 0)
9342 return SemaRef.Diag(FnDecl->getLocation(),
9343 diag::err_operator_new_delete_too_few_parameters)
9344 << FnDecl->getDeclName();
9345
9346 // Check the the first parameter type is not dependent.
9347 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9348 if (FirstParamType->isDependentType())
9349 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9350 << FnDecl->getDeclName() << ExpectedFirstParamType;
9351
9352 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009353 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009354 ExpectedFirstParamType)
9355 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9356 << FnDecl->getDeclName() << ExpectedFirstParamType;
9357
9358 return false;
9359}
9360
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009361static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009362CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009363 // C++ [basic.stc.dynamic.allocation]p1:
9364 // A program is ill-formed if an allocation function is declared in a
9365 // namespace scope other than global scope or declared static in global
9366 // scope.
9367 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9368 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009369
9370 CanQualType SizeTy =
9371 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9372
9373 // C++ [basic.stc.dynamic.allocation]p1:
9374 // The return type shall be void*. The first parameter shall have type
9375 // std::size_t.
9376 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9377 SizeTy,
9378 diag::err_operator_new_dependent_param_type,
9379 diag::err_operator_new_param_type))
9380 return true;
9381
9382 // C++ [basic.stc.dynamic.allocation]p1:
9383 // The first parameter shall not have an associated default argument.
9384 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009385 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009386 diag::err_operator_new_default_arg)
9387 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9388
9389 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009390}
9391
9392static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009393CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9394 // C++ [basic.stc.dynamic.deallocation]p1:
9395 // A program is ill-formed if deallocation functions are declared in a
9396 // namespace scope other than global scope or declared static in global
9397 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009398 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9399 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009400
9401 // C++ [basic.stc.dynamic.deallocation]p2:
9402 // Each deallocation function shall return void and its first parameter
9403 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009404 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9405 SemaRef.Context.VoidPtrTy,
9406 diag::err_operator_delete_dependent_param_type,
9407 diag::err_operator_delete_param_type))
9408 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009409
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009410 return false;
9411}
9412
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009413/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9414/// of this overloaded operator is well-formed. If so, returns false;
9415/// otherwise, emits appropriate diagnostics and returns true.
9416bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009417 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009418 "Expected an overloaded operator declaration");
9419
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009420 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9421
Mike Stump1eb44332009-09-09 15:08:12 +00009422 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009423 // The allocation and deallocation functions, operator new,
9424 // operator new[], operator delete and operator delete[], are
9425 // described completely in 3.7.3. The attributes and restrictions
9426 // found in the rest of this subclause do not apply to them unless
9427 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009428 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009429 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009430
Anders Carlssona3ccda52009-12-12 00:26:23 +00009431 if (Op == OO_New || Op == OO_Array_New)
9432 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009433
9434 // C++ [over.oper]p6:
9435 // An operator function shall either be a non-static member
9436 // function or be a non-member function and have at least one
9437 // parameter whose type is a class, a reference to a class, an
9438 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009439 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9440 if (MethodDecl->isStatic())
9441 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009442 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009443 } else {
9444 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009445 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9446 ParamEnd = FnDecl->param_end();
9447 Param != ParamEnd; ++Param) {
9448 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009449 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9450 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009451 ClassOrEnumParam = true;
9452 break;
9453 }
9454 }
9455
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009456 if (!ClassOrEnumParam)
9457 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009458 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009459 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009460 }
9461
9462 // C++ [over.oper]p8:
9463 // An operator function cannot have default arguments (8.3.6),
9464 // except where explicitly stated below.
9465 //
Mike Stump1eb44332009-09-09 15:08:12 +00009466 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009467 // (C++ [over.call]p1).
9468 if (Op != OO_Call) {
9469 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9470 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009471 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009472 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009473 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009474 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009475 }
9476 }
9477
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009478 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9479 { false, false, false }
9480#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9481 , { Unary, Binary, MemberOnly }
9482#include "clang/Basic/OperatorKinds.def"
9483 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009484
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009485 bool CanBeUnaryOperator = OperatorUses[Op][0];
9486 bool CanBeBinaryOperator = OperatorUses[Op][1];
9487 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009488
9489 // C++ [over.oper]p8:
9490 // [...] Operator functions cannot have more or fewer parameters
9491 // than the number required for the corresponding operator, as
9492 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009493 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009494 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009495 if (Op != OO_Call &&
9496 ((NumParams == 1 && !CanBeUnaryOperator) ||
9497 (NumParams == 2 && !CanBeBinaryOperator) ||
9498 (NumParams < 1) || (NumParams > 2))) {
9499 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009500 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009501 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009502 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009503 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009504 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009505 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009506 assert(CanBeBinaryOperator &&
9507 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009508 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009509 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009510
Chris Lattner416e46f2008-11-21 07:57:12 +00009511 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009512 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009513 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009514
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009515 // Overloaded operators other than operator() cannot be variadic.
9516 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009517 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009518 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009519 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009520 }
9521
9522 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009523 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9524 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009525 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009526 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009527 }
9528
9529 // C++ [over.inc]p1:
9530 // The user-defined function called operator++ implements the
9531 // prefix and postfix ++ operator. If this function is a member
9532 // function with no parameters, or a non-member function with one
9533 // parameter of class or enumeration type, it defines the prefix
9534 // increment operator ++ for objects of that type. If the function
9535 // is a member function with one parameter (which shall be of type
9536 // int) or a non-member function with two parameters (the second
9537 // of which shall be of type int), it defines the postfix
9538 // increment operator ++ for objects of that type.
9539 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9540 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9541 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009542 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009543 ParamIsInt = BT->getKind() == BuiltinType::Int;
9544
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009545 if (!ParamIsInt)
9546 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009547 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009548 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009549 }
9550
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009551 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009552}
Chris Lattner5a003a42008-12-17 07:09:26 +00009553
Sean Hunta6c058d2010-01-13 09:01:02 +00009554/// CheckLiteralOperatorDeclaration - Check whether the declaration
9555/// of this literal operator function is well-formed. If so, returns
9556/// false; otherwise, emits appropriate diagnostics and returns true.
9557bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9558 DeclContext *DC = FnDecl->getDeclContext();
9559 Decl::Kind Kind = DC->getDeclKind();
9560 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9561 Kind != Decl::LinkageSpec) {
9562 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9563 << FnDecl->getDeclName();
9564 return true;
9565 }
9566
9567 bool Valid = false;
9568
Sean Hunt216c2782010-04-07 23:11:06 +00009569 // template <char...> type operator "" name() is the only valid template
9570 // signature, and the only valid signature with no parameters.
9571 if (FnDecl->param_size() == 0) {
9572 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9573 // Must have only one template parameter
9574 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9575 if (Params->size() == 1) {
9576 NonTypeTemplateParmDecl *PmDecl =
9577 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009578
Sean Hunt216c2782010-04-07 23:11:06 +00009579 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009580 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9581 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9582 Valid = true;
9583 }
9584 }
9585 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009586 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009587 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9588
Sean Hunta6c058d2010-01-13 09:01:02 +00009589 QualType T = (*Param)->getType();
9590
Sean Hunt30019c02010-04-07 22:57:35 +00009591 // unsigned long long int, long double, and any character type are allowed
9592 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009593 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9594 Context.hasSameType(T, Context.LongDoubleTy) ||
9595 Context.hasSameType(T, Context.CharTy) ||
9596 Context.hasSameType(T, Context.WCharTy) ||
9597 Context.hasSameType(T, Context.Char16Ty) ||
9598 Context.hasSameType(T, Context.Char32Ty)) {
9599 if (++Param == FnDecl->param_end())
9600 Valid = true;
9601 goto FinishedParams;
9602 }
9603
Sean Hunt30019c02010-04-07 22:57:35 +00009604 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009605 const PointerType *PT = T->getAs<PointerType>();
9606 if (!PT)
9607 goto FinishedParams;
9608 T = PT->getPointeeType();
9609 if (!T.isConstQualified())
9610 goto FinishedParams;
9611 T = T.getUnqualifiedType();
9612
9613 // Move on to the second parameter;
9614 ++Param;
9615
9616 // If there is no second parameter, the first must be a const char *
9617 if (Param == FnDecl->param_end()) {
9618 if (Context.hasSameType(T, Context.CharTy))
9619 Valid = true;
9620 goto FinishedParams;
9621 }
9622
9623 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9624 // are allowed as the first parameter to a two-parameter function
9625 if (!(Context.hasSameType(T, Context.CharTy) ||
9626 Context.hasSameType(T, Context.WCharTy) ||
9627 Context.hasSameType(T, Context.Char16Ty) ||
9628 Context.hasSameType(T, Context.Char32Ty)))
9629 goto FinishedParams;
9630
9631 // The second and final parameter must be an std::size_t
9632 T = (*Param)->getType().getUnqualifiedType();
9633 if (Context.hasSameType(T, Context.getSizeType()) &&
9634 ++Param == FnDecl->param_end())
9635 Valid = true;
9636 }
9637
9638 // FIXME: This diagnostic is absolutely terrible.
9639FinishedParams:
9640 if (!Valid) {
9641 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9642 << FnDecl->getDeclName();
9643 return true;
9644 }
9645
Douglas Gregor1155c422011-08-30 22:40:35 +00009646 StringRef LiteralName
9647 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9648 if (LiteralName[0] != '_') {
9649 // C++0x [usrlit.suffix]p1:
9650 // Literal suffix identifiers that do not start with an underscore are
9651 // reserved for future standardization.
9652 bool IsHexFloat = true;
9653 if (LiteralName.size() > 1 &&
9654 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9655 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9656 if (!isdigit(LiteralName[I])) {
9657 IsHexFloat = false;
9658 break;
9659 }
9660 }
9661 }
9662
9663 if (IsHexFloat)
9664 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9665 << LiteralName;
9666 else
9667 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9668 }
9669
Sean Hunta6c058d2010-01-13 09:01:02 +00009670 return false;
9671}
9672
Douglas Gregor074149e2009-01-05 19:45:36 +00009673/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9674/// linkage specification, including the language and (if present)
9675/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9676/// the location of the language string literal, which is provided
9677/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9678/// the '{' brace. Otherwise, this linkage specification does not
9679/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009680Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9681 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009682 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009683 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009684 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009685 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009686 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009687 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009688 Language = LinkageSpecDecl::lang_cxx;
9689 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009690 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009691 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009692 }
Mike Stump1eb44332009-09-09 15:08:12 +00009693
Chris Lattnercc98eac2008-12-17 07:13:27 +00009694 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009695
Douglas Gregor074149e2009-01-05 19:45:36 +00009696 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009697 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009698 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009699 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009700 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009701}
9702
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009703/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009704/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9705/// valid, it's the position of the closing '}' brace in a linkage
9706/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009707Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009708 Decl *LinkageSpec,
9709 SourceLocation RBraceLoc) {
9710 if (LinkageSpec) {
9711 if (RBraceLoc.isValid()) {
9712 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9713 LSDecl->setRBraceLoc(RBraceLoc);
9714 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009715 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009716 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009717 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009718}
9719
Douglas Gregord308e622009-05-18 20:51:54 +00009720/// \brief Perform semantic analysis for the variable declaration that
9721/// occurs within a C++ catch clause, returning the newly-created
9722/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009723VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009724 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009725 SourceLocation StartLoc,
9726 SourceLocation Loc,
9727 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009728 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009729 QualType ExDeclType = TInfo->getType();
9730
Sebastian Redl4b07b292008-12-22 19:15:10 +00009731 // Arrays and functions decay.
9732 if (ExDeclType->isArrayType())
9733 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9734 else if (ExDeclType->isFunctionType())
9735 ExDeclType = Context.getPointerType(ExDeclType);
9736
9737 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9738 // The exception-declaration shall not denote a pointer or reference to an
9739 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009740 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009741 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009742 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009743 Invalid = true;
9744 }
Douglas Gregord308e622009-05-18 20:51:54 +00009745
Sebastian Redl4b07b292008-12-22 19:15:10 +00009746 QualType BaseType = ExDeclType;
9747 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009748 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009749 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009750 BaseType = Ptr->getPointeeType();
9751 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009752 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009753 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009754 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009755 BaseType = Ref->getPointeeType();
9756 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009757 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009758 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009759 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009760 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009761 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009762
Mike Stump1eb44332009-09-09 15:08:12 +00009763 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009764 RequireNonAbstractType(Loc, ExDeclType,
9765 diag::err_abstract_type_in_decl,
9766 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009767 Invalid = true;
9768
John McCall5a180392010-07-24 00:37:23 +00009769 // Only the non-fragile NeXT runtime currently supports C++ catches
9770 // of ObjC types, and no runtime supports catching ObjC types by value.
9771 if (!Invalid && getLangOptions().ObjC1) {
9772 QualType T = ExDeclType;
9773 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9774 T = RT->getPointeeType();
9775
9776 if (T->isObjCObjectType()) {
9777 Diag(Loc, diag::err_objc_object_catch);
9778 Invalid = true;
9779 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009780 if (!getLangOptions().ObjCNonFragileABI)
9781 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009782 }
9783 }
9784
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009785 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9786 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009787 ExDecl->setExceptionVariable(true);
9788
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009789 // In ARC, infer 'retaining' for variables of retainable type.
9790 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9791 Invalid = true;
9792
Douglas Gregorc41b8782011-07-06 18:14:43 +00009793 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009794 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009795 // C++ [except.handle]p16:
9796 // The object declared in an exception-declaration or, if the
9797 // exception-declaration does not specify a name, a temporary (12.2) is
9798 // copy-initialized (8.5) from the exception object. [...]
9799 // The object is destroyed when the handler exits, after the destruction
9800 // of any automatic objects initialized within the handler.
9801 //
9802 // We just pretend to initialize the object with itself, then make sure
9803 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009804 QualType initType = ExDeclType;
9805
9806 InitializedEntity entity =
9807 InitializedEntity::InitializeVariable(ExDecl);
9808 InitializationKind initKind =
9809 InitializationKind::CreateCopy(Loc, SourceLocation());
9810
9811 Expr *opaqueValue =
9812 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9813 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9814 ExprResult result = sequence.Perform(*this, entity, initKind,
9815 MultiExprArg(&opaqueValue, 1));
9816 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009817 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009818 else {
9819 // If the constructor used was non-trivial, set this as the
9820 // "initializer".
9821 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9822 if (!construct->getConstructor()->isTrivial()) {
9823 Expr *init = MaybeCreateExprWithCleanups(construct);
9824 ExDecl->setInit(init);
9825 }
9826
9827 // And make sure it's destructable.
9828 FinalizeVarWithDestructor(ExDecl, recordType);
9829 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009830 }
9831 }
9832
Douglas Gregord308e622009-05-18 20:51:54 +00009833 if (Invalid)
9834 ExDecl->setInvalidDecl();
9835
9836 return ExDecl;
9837}
9838
9839/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9840/// handler.
John McCalld226f652010-08-21 09:40:31 +00009841Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009842 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009843 bool Invalid = D.isInvalidType();
9844
9845 // Check for unexpanded parameter packs.
9846 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9847 UPPC_ExceptionType)) {
9848 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9849 D.getIdentifierLoc());
9850 Invalid = true;
9851 }
9852
Sebastian Redl4b07b292008-12-22 19:15:10 +00009853 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009854 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009855 LookupOrdinaryName,
9856 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009857 // The scope should be freshly made just for us. There is just no way
9858 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009859 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009860 if (PrevDecl->isTemplateParameter()) {
9861 // Maybe we will complain about the shadowed template parameter.
9862 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009863 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009864 }
9865 }
9866
Chris Lattnereaaebc72009-04-25 08:06:05 +00009867 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009868 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9869 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009870 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009871 }
9872
Douglas Gregor83cb9422010-09-09 17:09:21 +00009873 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009874 D.getSourceRange().getBegin(),
9875 D.getIdentifierLoc(),
9876 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009877 if (Invalid)
9878 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009879
Sebastian Redl4b07b292008-12-22 19:15:10 +00009880 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009881 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009882 PushOnScopeChains(ExDecl, S);
9883 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009884 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009885
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009886 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009887 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009888}
Anders Carlssonfb311762009-03-14 00:25:26 +00009889
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009890Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009891 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009892 Expr *AssertMessageExpr_,
9893 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009894 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009895
Anders Carlssonc3082412009-03-14 00:33:21 +00009896 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009897 llvm::APSInt Cond;
9898 if (VerifyIntegerConstantExpression(AssertExpr, &Cond,
9899 diag::err_static_assert_expression_is_not_constant,
9900 /*AllowFold=*/false))
John McCalld226f652010-08-21 09:40:31 +00009901 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009902
Richard Smithdaaefc52011-12-14 23:32:26 +00009903 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009904 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009905 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009906 }
Mike Stump1eb44332009-09-09 15:08:12 +00009907
Douglas Gregor399ad972010-12-15 23:55:21 +00009908 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9909 return 0;
9910
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009911 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9912 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009913
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009914 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009915 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009916}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009917
Douglas Gregor1d869352010-04-07 16:53:43 +00009918/// \brief Perform semantic analysis of the given friend type declaration.
9919///
9920/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009921FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9922 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009923 TypeSourceInfo *TSInfo) {
9924 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9925
9926 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009927 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009928
Richard Smith6b130222011-10-18 21:39:00 +00009929 // C++03 [class.friend]p2:
9930 // An elaborated-type-specifier shall be used in a friend declaration
9931 // for a class.*
9932 //
9933 // * The class-key of the elaborated-type-specifier is required.
9934 if (!ActiveTemplateInstantiations.empty()) {
9935 // Do not complain about the form of friend template types during
9936 // template instantiation; we will already have complained when the
9937 // template was declared.
9938 } else if (!T->isElaboratedTypeSpecifier()) {
9939 // If we evaluated the type to a record type, suggest putting
9940 // a tag in front.
9941 if (const RecordType *RT = T->getAs<RecordType>()) {
9942 RecordDecl *RD = RT->getDecl();
9943
9944 std::string InsertionText = std::string(" ") + RD->getKindName();
9945
9946 Diag(TypeRange.getBegin(),
9947 getLangOptions().CPlusPlus0x ?
9948 diag::warn_cxx98_compat_unelaborated_friend_type :
9949 diag::ext_unelaborated_friend_type)
9950 << (unsigned) RD->getTagKind()
9951 << T
9952 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9953 InsertionText);
9954 } else {
9955 Diag(FriendLoc,
9956 getLangOptions().CPlusPlus0x ?
9957 diag::warn_cxx98_compat_nonclass_type_friend :
9958 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009959 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009960 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009961 }
Richard Smith6b130222011-10-18 21:39:00 +00009962 } else if (T->getAs<EnumType>()) {
9963 Diag(FriendLoc,
9964 getLangOptions().CPlusPlus0x ?
9965 diag::warn_cxx98_compat_enum_friend :
9966 diag::ext_enum_friend)
9967 << T
9968 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009969 }
9970
Douglas Gregor06245bf2010-04-07 17:57:12 +00009971 // C++0x [class.friend]p3:
9972 // If the type specifier in a friend declaration designates a (possibly
9973 // cv-qualified) class type, that class is declared as a friend; otherwise,
9974 // the friend declaration is ignored.
9975
9976 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9977 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009978
Abramo Bagnara0216df82011-10-29 20:52:52 +00009979 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009980}
9981
John McCall9a34edb2010-10-19 01:40:49 +00009982/// Handle a friend tag declaration where the scope specifier was
9983/// templated.
9984Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9985 unsigned TagSpec, SourceLocation TagLoc,
9986 CXXScopeSpec &SS,
9987 IdentifierInfo *Name, SourceLocation NameLoc,
9988 AttributeList *Attr,
9989 MultiTemplateParamsArg TempParamLists) {
9990 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9991
9992 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009993 bool Invalid = false;
9994
9995 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009996 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009997 TempParamLists.get(),
9998 TempParamLists.size(),
9999 /*friend*/ true,
10000 isExplicitSpecialization,
10001 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010002 if (TemplateParams->size() > 0) {
10003 // This is a declaration of a class template.
10004 if (Invalid)
10005 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010006
Eric Christopher4110e132011-07-21 05:34:24 +000010007 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10008 SS, Name, NameLoc, Attr,
10009 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010010 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010011 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010012 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010013 } else {
10014 // The "template<>" header is extraneous.
10015 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10016 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10017 isExplicitSpecialization = true;
10018 }
10019 }
10020
10021 if (Invalid) return 0;
10022
John McCall9a34edb2010-10-19 01:40:49 +000010023 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010024 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010025 if (TempParamLists.get()[I]->size()) {
10026 isAllExplicitSpecializations = false;
10027 break;
10028 }
10029 }
10030
10031 // FIXME: don't ignore attributes.
10032
10033 // If it's explicit specializations all the way down, just forget
10034 // about the template header and build an appropriate non-templated
10035 // friend. TODO: for source fidelity, remember the headers.
10036 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010037 if (SS.isEmpty()) {
10038 bool Owned = false;
10039 bool IsDependent = false;
10040 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10041 Attr, AS_public,
10042 /*ModulePrivateLoc=*/SourceLocation(),
10043 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010044 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010045 /*ScopedEnumUsesClassTag=*/false,
10046 /*UnderlyingType=*/TypeResult());
10047 }
10048
Douglas Gregor2494dd02011-03-01 01:34:45 +000010049 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010050 ElaboratedTypeKeyword Keyword
10051 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010052 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010053 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010054 if (T.isNull())
10055 return 0;
10056
10057 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10058 if (isa<DependentNameType>(T)) {
10059 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10060 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010061 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010062 TL.setNameLoc(NameLoc);
10063 } else {
10064 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10065 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010066 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010067 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10068 }
10069
10070 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10071 TSI, FriendLoc);
10072 Friend->setAccess(AS_public);
10073 CurContext->addDecl(Friend);
10074 return Friend;
10075 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010076
10077 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10078
10079
John McCall9a34edb2010-10-19 01:40:49 +000010080
10081 // Handle the case of a templated-scope friend class. e.g.
10082 // template <class T> class A<T>::B;
10083 // FIXME: we don't support these right now.
10084 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10085 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10086 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10087 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10088 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010089 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010090 TL.setNameLoc(NameLoc);
10091
10092 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10093 TSI, FriendLoc);
10094 Friend->setAccess(AS_public);
10095 Friend->setUnsupportedFriend(true);
10096 CurContext->addDecl(Friend);
10097 return Friend;
10098}
10099
10100
John McCalldd4a3b02009-09-16 22:47:08 +000010101/// Handle a friend type declaration. This works in tandem with
10102/// ActOnTag.
10103///
10104/// Notes on friend class templates:
10105///
10106/// We generally treat friend class declarations as if they were
10107/// declaring a class. So, for example, the elaborated type specifier
10108/// in a friend declaration is required to obey the restrictions of a
10109/// class-head (i.e. no typedefs in the scope chain), template
10110/// parameters are required to match up with simple template-ids, &c.
10111/// However, unlike when declaring a template specialization, it's
10112/// okay to refer to a template specialization without an empty
10113/// template parameter declaration, e.g.
10114/// friend class A<T>::B<unsigned>;
10115/// We permit this as a special case; if there are any template
10116/// parameters present at all, require proper matching, i.e.
10117/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010118Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010119 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010120 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010121
10122 assert(DS.isFriendSpecified());
10123 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10124
John McCalldd4a3b02009-09-16 22:47:08 +000010125 // Try to convert the decl specifier to a type. This works for
10126 // friend templates because ActOnTag never produces a ClassTemplateDecl
10127 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010128 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010129 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10130 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010131 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010132 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010133
Douglas Gregor6ccab972010-12-16 01:14:37 +000010134 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10135 return 0;
10136
John McCalldd4a3b02009-09-16 22:47:08 +000010137 // This is definitely an error in C++98. It's probably meant to
10138 // be forbidden in C++0x, too, but the specification is just
10139 // poorly written.
10140 //
10141 // The problem is with declarations like the following:
10142 // template <T> friend A<T>::foo;
10143 // where deciding whether a class C is a friend or not now hinges
10144 // on whether there exists an instantiation of A that causes
10145 // 'foo' to equal C. There are restrictions on class-heads
10146 // (which we declare (by fiat) elaborated friend declarations to
10147 // be) that makes this tractable.
10148 //
10149 // FIXME: handle "template <> friend class A<T>;", which
10150 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010151 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010152 Diag(Loc, diag::err_tagless_friend_type_template)
10153 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010154 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010155 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010156
John McCall02cace72009-08-28 07:59:38 +000010157 // C++98 [class.friend]p1: A friend of a class is a function
10158 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010159 // This is fixed in DR77, which just barely didn't make the C++03
10160 // deadline. It's also a very silly restriction that seriously
10161 // affects inner classes and which nobody else seems to implement;
10162 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010163 //
10164 // But note that we could warn about it: it's always useless to
10165 // friend one of your own members (it's not, however, worthless to
10166 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010167
John McCalldd4a3b02009-09-16 22:47:08 +000010168 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010169 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010170 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010171 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010172 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010173 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010174 DS.getFriendSpecLoc());
10175 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010176 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010177
10178 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010179 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010180
John McCalldd4a3b02009-09-16 22:47:08 +000010181 D->setAccess(AS_public);
10182 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010183
John McCalld226f652010-08-21 09:40:31 +000010184 return D;
John McCall02cace72009-08-28 07:59:38 +000010185}
10186
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010187Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010188 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010189 const DeclSpec &DS = D.getDeclSpec();
10190
10191 assert(DS.isFriendSpecified());
10192 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10193
10194 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010195 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010196
10197 // C++ [class.friend]p1
10198 // A friend of a class is a function or class....
10199 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010200 // It *doesn't* see through dependent types, which is correct
10201 // according to [temp.arg.type]p3:
10202 // If a declaration acquires a function type through a
10203 // type dependent on a template-parameter and this causes
10204 // a declaration that does not use the syntactic form of a
10205 // function declarator to have a function type, the program
10206 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010207 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010208 Diag(Loc, diag::err_unexpected_friend);
10209
10210 // It might be worthwhile to try to recover by creating an
10211 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010212 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010213 }
10214
10215 // C++ [namespace.memdef]p3
10216 // - If a friend declaration in a non-local class first declares a
10217 // class or function, the friend class or function is a member
10218 // of the innermost enclosing namespace.
10219 // - The name of the friend is not found by simple name lookup
10220 // until a matching declaration is provided in that namespace
10221 // scope (either before or after the class declaration granting
10222 // friendship).
10223 // - If a friend function is called, its name may be found by the
10224 // name lookup that considers functions from namespaces and
10225 // classes associated with the types of the function arguments.
10226 // - When looking for a prior declaration of a class or a function
10227 // declared as a friend, scopes outside the innermost enclosing
10228 // namespace scope are not considered.
10229
John McCall337ec3d2010-10-12 23:13:28 +000010230 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10232 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010233 assert(Name);
10234
Douglas Gregor6ccab972010-12-16 01:14:37 +000010235 // Check for unexpanded parameter packs.
10236 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10237 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10238 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10239 return 0;
10240
John McCall67d1a672009-08-06 02:15:43 +000010241 // The context we found the declaration in, or in which we should
10242 // create the declaration.
10243 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010244 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010245 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010246 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010247
John McCall337ec3d2010-10-12 23:13:28 +000010248 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010249
John McCall337ec3d2010-10-12 23:13:28 +000010250 // There are four cases here.
10251 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010252 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010253 // there as appropriate.
10254 // Recover from invalid scope qualifiers as if they just weren't there.
10255 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010256 // C++0x [namespace.memdef]p3:
10257 // If the name in a friend declaration is neither qualified nor
10258 // a template-id and the declaration is a function or an
10259 // elaborated-type-specifier, the lookup to determine whether
10260 // the entity has been previously declared shall not consider
10261 // any scopes outside the innermost enclosing namespace.
10262 // C++0x [class.friend]p11:
10263 // If a friend declaration appears in a local class and the name
10264 // specified is an unqualified name, a prior declaration is
10265 // looked up without considering scopes that are outside the
10266 // innermost enclosing non-class scope. For a friend function
10267 // declaration, if there is no prior declaration, the program is
10268 // ill-formed.
10269 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010270 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010271
John McCall29ae6e52010-10-13 05:45:15 +000010272 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010273 DC = CurContext;
10274 while (true) {
10275 // Skip class contexts. If someone can cite chapter and verse
10276 // for this behavior, that would be nice --- it's what GCC and
10277 // EDG do, and it seems like a reasonable intent, but the spec
10278 // really only says that checks for unqualified existing
10279 // declarations should stop at the nearest enclosing namespace,
10280 // not that they should only consider the nearest enclosing
10281 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010282 while (DC->isRecord())
10283 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010284
John McCall68263142009-11-18 22:49:29 +000010285 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010286
10287 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010288 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010289 break;
John McCall29ae6e52010-10-13 05:45:15 +000010290
John McCall8a407372010-10-14 22:22:28 +000010291 if (isTemplateId) {
10292 if (isa<TranslationUnitDecl>(DC)) break;
10293 } else {
10294 if (DC->isFileContext()) break;
10295 }
John McCall67d1a672009-08-06 02:15:43 +000010296 DC = DC->getParent();
10297 }
10298
10299 // C++ [class.friend]p1: A friend of a class is a function or
10300 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010301 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010302 // Most C++ 98 compilers do seem to give an error here, so
10303 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010304 if (!Previous.empty() && DC->Equals(CurContext))
10305 Diag(DS.getFriendSpecLoc(),
10306 getLangOptions().CPlusPlus0x ?
10307 diag::warn_cxx98_compat_friend_is_member :
10308 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010309
John McCall380aaa42010-10-13 06:22:15 +000010310 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010311
Douglas Gregor883af832011-10-10 01:11:59 +000010312 // C++ [class.friend]p6:
10313 // A function can be defined in a friend declaration of a class if and
10314 // only if the class is a non-local class (9.8), the function name is
10315 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010316 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010317 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10318 }
10319
John McCall337ec3d2010-10-12 23:13:28 +000010320 // - There's a non-dependent scope specifier, in which case we
10321 // compute it and do a previous lookup there for a function
10322 // or function template.
10323 } else if (!SS.getScopeRep()->isDependent()) {
10324 DC = computeDeclContext(SS);
10325 if (!DC) return 0;
10326
10327 if (RequireCompleteDeclContext(SS, DC)) return 0;
10328
10329 LookupQualifiedName(Previous, DC);
10330
10331 // Ignore things found implicitly in the wrong scope.
10332 // TODO: better diagnostics for this case. Suggesting the right
10333 // qualified scope would be nice...
10334 LookupResult::Filter F = Previous.makeFilter();
10335 while (F.hasNext()) {
10336 NamedDecl *D = F.next();
10337 if (!DC->InEnclosingNamespaceSetOf(
10338 D->getDeclContext()->getRedeclContext()))
10339 F.erase();
10340 }
10341 F.done();
10342
10343 if (Previous.empty()) {
10344 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010345 Diag(Loc, diag::err_qualified_friend_not_found)
10346 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010347 return 0;
10348 }
10349
10350 // C++ [class.friend]p1: A friend of a class is a function or
10351 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010352 if (DC->Equals(CurContext))
10353 Diag(DS.getFriendSpecLoc(),
10354 getLangOptions().CPlusPlus0x ?
10355 diag::warn_cxx98_compat_friend_is_member :
10356 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010357
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010358 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010359 // C++ [class.friend]p6:
10360 // A function can be defined in a friend declaration of a class if and
10361 // only if the class is a non-local class (9.8), the function name is
10362 // unqualified, and the function has namespace scope.
10363 SemaDiagnosticBuilder DB
10364 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10365
10366 DB << SS.getScopeRep();
10367 if (DC->isFileContext())
10368 DB << FixItHint::CreateRemoval(SS.getRange());
10369 SS.clear();
10370 }
John McCall337ec3d2010-10-12 23:13:28 +000010371
10372 // - There's a scope specifier that does not match any template
10373 // parameter lists, in which case we use some arbitrary context,
10374 // create a method or method template, and wait for instantiation.
10375 // - There's a scope specifier that does match some template
10376 // parameter lists, which we don't handle right now.
10377 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010378 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010379 // C++ [class.friend]p6:
10380 // A function can be defined in a friend declaration of a class if and
10381 // only if the class is a non-local class (9.8), the function name is
10382 // unqualified, and the function has namespace scope.
10383 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10384 << SS.getScopeRep();
10385 }
10386
John McCall337ec3d2010-10-12 23:13:28 +000010387 DC = CurContext;
10388 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010389 }
Douglas Gregor883af832011-10-10 01:11:59 +000010390
John McCall29ae6e52010-10-13 05:45:15 +000010391 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010392 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010393 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10394 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10395 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010396 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010397 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10398 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010399 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010400 }
John McCall67d1a672009-08-06 02:15:43 +000010401 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010402
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010403 // FIXME: This is an egregious hack to cope with cases where the scope stack
10404 // does not contain the declaration context, i.e., in an out-of-line
10405 // definition of a class.
10406 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10407 if (!DCScope) {
10408 FakeDCScope.setEntity(DC);
10409 DCScope = &FakeDCScope;
10410 }
10411
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010412 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010413 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10414 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010415 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010416
Douglas Gregor182ddf02009-09-28 00:08:27 +000010417 assert(ND->getDeclContext() == DC);
10418 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010419
John McCallab88d972009-08-31 22:39:49 +000010420 // Add the function declaration to the appropriate lookup tables,
10421 // adjusting the redeclarations list as necessary. We don't
10422 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010423 //
John McCallab88d972009-08-31 22:39:49 +000010424 // Also update the scope-based lookup if the target context's
10425 // lookup context is in lexical scope.
10426 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010427 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010428 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010429 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010430 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010431 }
John McCall02cace72009-08-28 07:59:38 +000010432
10433 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010434 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010435 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010436 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010437 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010438
John McCall337ec3d2010-10-12 23:13:28 +000010439 if (ND->isInvalidDecl())
10440 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010441 else {
10442 FunctionDecl *FD;
10443 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10444 FD = FTD->getTemplatedDecl();
10445 else
10446 FD = cast<FunctionDecl>(ND);
10447
10448 // Mark templated-scope function declarations as unsupported.
10449 if (FD->getNumTemplateParameterLists())
10450 FrD->setUnsupportedFriend(true);
10451 }
John McCall337ec3d2010-10-12 23:13:28 +000010452
John McCalld226f652010-08-21 09:40:31 +000010453 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010454}
10455
John McCalld226f652010-08-21 09:40:31 +000010456void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10457 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010458
Sebastian Redl50de12f2009-03-24 22:27:57 +000010459 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10460 if (!Fn) {
10461 Diag(DelLoc, diag::err_deleted_non_function);
10462 return;
10463 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010464 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010465 Diag(DelLoc, diag::err_deleted_decl_not_first);
10466 Diag(Prev->getLocation(), diag::note_previous_declaration);
10467 // If the declaration wasn't the first, we delete the function anyway for
10468 // recovery.
10469 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010470 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010471}
Sebastian Redl13e88542009-04-27 21:33:24 +000010472
Sean Hunte4246a62011-05-12 06:15:49 +000010473void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10474 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10475
10476 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010477 if (MD->getParent()->isDependentType()) {
10478 MD->setDefaulted();
10479 MD->setExplicitlyDefaulted();
10480 return;
10481 }
10482
Sean Hunte4246a62011-05-12 06:15:49 +000010483 CXXSpecialMember Member = getSpecialMember(MD);
10484 if (Member == CXXInvalid) {
10485 Diag(DefaultLoc, diag::err_default_special_members);
10486 return;
10487 }
10488
10489 MD->setDefaulted();
10490 MD->setExplicitlyDefaulted();
10491
Sean Huntcd10dec2011-05-23 23:14:04 +000010492 // If this definition appears within the record, do the checking when
10493 // the record is complete.
10494 const FunctionDecl *Primary = MD;
10495 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10496 // Find the uninstantiated declaration that actually had the '= default'
10497 // on it.
10498 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10499
10500 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010501 return;
10502
10503 switch (Member) {
10504 case CXXDefaultConstructor: {
10505 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10506 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010507 if (!CD->isInvalidDecl())
10508 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10509 break;
10510 }
10511
10512 case CXXCopyConstructor: {
10513 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10514 CheckExplicitlyDefaultedCopyConstructor(CD);
10515 if (!CD->isInvalidDecl())
10516 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010517 break;
10518 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010519
Sean Hunt2b188082011-05-14 05:23:28 +000010520 case CXXCopyAssignment: {
10521 CheckExplicitlyDefaultedCopyAssignment(MD);
10522 if (!MD->isInvalidDecl())
10523 DefineImplicitCopyAssignment(DefaultLoc, MD);
10524 break;
10525 }
10526
Sean Huntcb45a0f2011-05-12 22:46:25 +000010527 case CXXDestructor: {
10528 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10529 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010530 if (!DD->isInvalidDecl())
10531 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010532 break;
10533 }
10534
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010535 case CXXMoveConstructor: {
10536 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10537 CheckExplicitlyDefaultedMoveConstructor(CD);
10538 if (!CD->isInvalidDecl())
10539 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010540 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010541 }
Sean Hunt82713172011-05-25 23:16:36 +000010542
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010543 case CXXMoveAssignment: {
10544 CheckExplicitlyDefaultedMoveAssignment(MD);
10545 if (!MD->isInvalidDecl())
10546 DefineImplicitMoveAssignment(DefaultLoc, MD);
10547 break;
10548 }
10549
10550 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010551 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010552 }
10553 } else {
10554 Diag(DefaultLoc, diag::err_default_special_members);
10555 }
10556}
10557
Sebastian Redl13e88542009-04-27 21:33:24 +000010558static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010559 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010560 Stmt *SubStmt = *CI;
10561 if (!SubStmt)
10562 continue;
10563 if (isa<ReturnStmt>(SubStmt))
10564 Self.Diag(SubStmt->getSourceRange().getBegin(),
10565 diag::err_return_in_constructor_handler);
10566 if (!isa<Expr>(SubStmt))
10567 SearchForReturnInStmt(Self, SubStmt);
10568 }
10569}
10570
10571void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10572 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10573 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10574 SearchForReturnInStmt(*this, Handler);
10575 }
10576}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010577
Mike Stump1eb44332009-09-09 15:08:12 +000010578bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010579 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010580 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10581 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010582
Chandler Carruth73857792010-02-15 11:53:20 +000010583 if (Context.hasSameType(NewTy, OldTy) ||
10584 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010585 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010586
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010587 // Check if the return types are covariant
10588 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010589
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010590 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010591 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10592 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010593 NewClassTy = NewPT->getPointeeType();
10594 OldClassTy = OldPT->getPointeeType();
10595 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010596 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10597 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10598 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10599 NewClassTy = NewRT->getPointeeType();
10600 OldClassTy = OldRT->getPointeeType();
10601 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010602 }
10603 }
Mike Stump1eb44332009-09-09 15:08:12 +000010604
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010605 // The return types aren't either both pointers or references to a class type.
10606 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010607 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010608 diag::err_different_return_type_for_overriding_virtual_function)
10609 << New->getDeclName() << NewTy << OldTy;
10610 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010611
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010612 return true;
10613 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010614
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010615 // C++ [class.virtual]p6:
10616 // If the return type of D::f differs from the return type of B::f, the
10617 // class type in the return type of D::f shall be complete at the point of
10618 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010619 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10620 if (!RT->isBeingDefined() &&
10621 RequireCompleteType(New->getLocation(), NewClassTy,
10622 PDiag(diag::err_covariant_return_incomplete)
10623 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010624 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010625 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010626
Douglas Gregora4923eb2009-11-16 21:35:15 +000010627 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010628 // Check if the new class derives from the old class.
10629 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10630 Diag(New->getLocation(),
10631 diag::err_covariant_return_not_derived)
10632 << New->getDeclName() << NewTy << OldTy;
10633 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10634 return true;
10635 }
Mike Stump1eb44332009-09-09 15:08:12 +000010636
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010637 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010638 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010639 diag::err_covariant_return_inaccessible_base,
10640 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10641 // FIXME: Should this point to the return type?
10642 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010643 // FIXME: this note won't trigger for delayed access control
10644 // diagnostics, and it's impossible to get an undelayed error
10645 // here from access control during the original parse because
10646 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010647 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10648 return true;
10649 }
10650 }
Mike Stump1eb44332009-09-09 15:08:12 +000010651
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010652 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010653 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010654 Diag(New->getLocation(),
10655 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010656 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010657 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10658 return true;
10659 };
Mike Stump1eb44332009-09-09 15:08:12 +000010660
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010661
10662 // The new class type must have the same or less qualifiers as the old type.
10663 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10664 Diag(New->getLocation(),
10665 diag::err_covariant_return_type_class_type_more_qualified)
10666 << New->getDeclName() << NewTy << OldTy;
10667 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10668 return true;
10669 };
Mike Stump1eb44332009-09-09 15:08:12 +000010670
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010671 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010672}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010673
Douglas Gregor4ba31362009-12-01 17:24:26 +000010674/// \brief Mark the given method pure.
10675///
10676/// \param Method the method to be marked pure.
10677///
10678/// \param InitRange the source range that covers the "0" initializer.
10679bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010680 SourceLocation EndLoc = InitRange.getEnd();
10681 if (EndLoc.isValid())
10682 Method->setRangeEnd(EndLoc);
10683
Douglas Gregor4ba31362009-12-01 17:24:26 +000010684 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10685 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010686 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010687 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010688
10689 if (!Method->isInvalidDecl())
10690 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10691 << Method->getDeclName() << InitRange;
10692 return true;
10693}
10694
John McCall731ad842009-12-19 09:28:58 +000010695/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10696/// an initializer for the out-of-line declaration 'Dcl'. The scope
10697/// is a fresh scope pushed for just this purpose.
10698///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010699/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10700/// static data member of class X, names should be looked up in the scope of
10701/// class X.
John McCalld226f652010-08-21 09:40:31 +000010702void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010703 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010704 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010705
John McCall731ad842009-12-19 09:28:58 +000010706 // We should only get called for declarations with scope specifiers, like:
10707 // int foo::bar;
10708 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010709 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010710}
10711
10712/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010713/// initializer for the out-of-line declaration 'D'.
10714void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010715 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010716 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010717
John McCall731ad842009-12-19 09:28:58 +000010718 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010719 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010720}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010721
10722/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10723/// C++ if/switch/while/for statement.
10724/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010725DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010726 // C++ 6.4p2:
10727 // The declarator shall not specify a function or an array.
10728 // The type-specifier-seq shall not contain typedef and shall not declare a
10729 // new class or enumeration.
10730 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10731 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010732
10733 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010734 if (!Dcl)
10735 return true;
10736
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010737 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10738 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010739 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010740 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010741 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010742
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010743 return Dcl;
10744}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010745
Douglas Gregordfe65432011-07-28 19:11:31 +000010746void Sema::LoadExternalVTableUses() {
10747 if (!ExternalSource)
10748 return;
10749
10750 SmallVector<ExternalVTableUse, 4> VTables;
10751 ExternalSource->ReadUsedVTables(VTables);
10752 SmallVector<VTableUse, 4> NewUses;
10753 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10754 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10755 = VTablesUsed.find(VTables[I].Record);
10756 // Even if a definition wasn't required before, it may be required now.
10757 if (Pos != VTablesUsed.end()) {
10758 if (!Pos->second && VTables[I].DefinitionRequired)
10759 Pos->second = true;
10760 continue;
10761 }
10762
10763 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10764 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10765 }
10766
10767 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10768}
10769
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010770void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10771 bool DefinitionRequired) {
10772 // Ignore any vtable uses in unevaluated operands or for classes that do
10773 // not have a vtable.
10774 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10775 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010776 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010777 return;
10778
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010779 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010780 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010781 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10782 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10783 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10784 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010785 // If we already had an entry, check to see if we are promoting this vtable
10786 // to required a definition. If so, we need to reappend to the VTableUses
10787 // list, since we may have already processed the first entry.
10788 if (DefinitionRequired && !Pos.first->second) {
10789 Pos.first->second = true;
10790 } else {
10791 // Otherwise, we can early exit.
10792 return;
10793 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010794 }
10795
10796 // Local classes need to have their virtual members marked
10797 // immediately. For all other classes, we mark their virtual members
10798 // at the end of the translation unit.
10799 if (Class->isLocalClass())
10800 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010801 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010802 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010803}
10804
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010805bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010806 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010807 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010808 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010809
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010810 // Note: The VTableUses vector could grow as a result of marking
10811 // the members of a class as "used", so we check the size each
10812 // time through the loop and prefer indices (with are stable) to
10813 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010814 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010815 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010816 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010817 if (!Class)
10818 continue;
10819
10820 SourceLocation Loc = VTableUses[I].second;
10821
10822 // If this class has a key function, but that key function is
10823 // defined in another translation unit, we don't need to emit the
10824 // vtable even though we're using it.
10825 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010826 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010827 switch (KeyFunction->getTemplateSpecializationKind()) {
10828 case TSK_Undeclared:
10829 case TSK_ExplicitSpecialization:
10830 case TSK_ExplicitInstantiationDeclaration:
10831 // The key function is in another translation unit.
10832 continue;
10833
10834 case TSK_ExplicitInstantiationDefinition:
10835 case TSK_ImplicitInstantiation:
10836 // We will be instantiating the key function.
10837 break;
10838 }
10839 } else if (!KeyFunction) {
10840 // If we have a class with no key function that is the subject
10841 // of an explicit instantiation declaration, suppress the
10842 // vtable; it will live with the explicit instantiation
10843 // definition.
10844 bool IsExplicitInstantiationDeclaration
10845 = Class->getTemplateSpecializationKind()
10846 == TSK_ExplicitInstantiationDeclaration;
10847 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10848 REnd = Class->redecls_end();
10849 R != REnd; ++R) {
10850 TemplateSpecializationKind TSK
10851 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10852 if (TSK == TSK_ExplicitInstantiationDeclaration)
10853 IsExplicitInstantiationDeclaration = true;
10854 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10855 IsExplicitInstantiationDeclaration = false;
10856 break;
10857 }
10858 }
10859
10860 if (IsExplicitInstantiationDeclaration)
10861 continue;
10862 }
10863
10864 // Mark all of the virtual members of this class as referenced, so
10865 // that we can build a vtable. Then, tell the AST consumer that a
10866 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010867 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010868 MarkVirtualMembersReferenced(Loc, Class);
10869 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10870 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10871
10872 // Optionally warn if we're emitting a weak vtable.
10873 if (Class->getLinkage() == ExternalLinkage &&
10874 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010875 const FunctionDecl *KeyFunctionDef = 0;
10876 if (!KeyFunction ||
10877 (KeyFunction->hasBody(KeyFunctionDef) &&
10878 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010879 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10880 TSK_ExplicitInstantiationDefinition
10881 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10882 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010883 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010884 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010885 VTableUses.clear();
10886
Douglas Gregor78844032011-04-22 22:25:37 +000010887 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010888}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010889
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010890void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10891 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010892 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10893 e = RD->method_end(); i != e; ++i) {
10894 CXXMethodDecl *MD = *i;
10895
10896 // C++ [basic.def.odr]p2:
10897 // [...] A virtual member function is used if it is not pure. [...]
10898 if (MD->isVirtual() && !MD->isPure())
10899 MarkDeclarationReferenced(Loc, MD);
10900 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010901
10902 // Only classes that have virtual bases need a VTT.
10903 if (RD->getNumVBases() == 0)
10904 return;
10905
10906 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10907 e = RD->bases_end(); i != e; ++i) {
10908 const CXXRecordDecl *Base =
10909 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010910 if (Base->getNumVBases() == 0)
10911 continue;
10912 MarkVirtualMembersReferenced(Loc, Base);
10913 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010914}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010915
10916/// SetIvarInitializers - This routine builds initialization ASTs for the
10917/// Objective-C implementation whose ivars need be initialized.
10918void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10919 if (!getLangOptions().CPlusPlus)
10920 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010921 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010922 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010923 CollectIvarsToConstructOrDestruct(OID, ivars);
10924 if (ivars.empty())
10925 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010926 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010927 for (unsigned i = 0; i < ivars.size(); i++) {
10928 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010929 if (Field->isInvalidDecl())
10930 continue;
10931
Sean Huntcbb67482011-01-08 20:30:50 +000010932 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010933 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10934 InitializationKind InitKind =
10935 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10936
10937 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010938 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010939 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010940 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010941 // Note, MemberInit could actually come back empty if no initialization
10942 // is required (e.g., because it would call a trivial default constructor)
10943 if (!MemberInit.get() || MemberInit.isInvalid())
10944 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010945
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010946 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010947 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10948 SourceLocation(),
10949 MemberInit.takeAs<Expr>(),
10950 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010951 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010952
10953 // Be sure that the destructor is accessible and is marked as referenced.
10954 if (const RecordType *RecordTy
10955 = Context.getBaseElementType(Field->getType())
10956 ->getAs<RecordType>()) {
10957 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010958 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010959 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10960 CheckDestructorAccess(Field->getLocation(), Destructor,
10961 PDiag(diag::err_access_dtor_ivar)
10962 << Context.getBaseElementType(Field->getType()));
10963 }
10964 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010965 }
10966 ObjCImplementation->setIvarInitializers(Context,
10967 AllToInit.data(), AllToInit.size());
10968 }
10969}
Sean Huntfe57eef2011-05-04 05:57:24 +000010970
Sean Huntebcbe1d2011-05-04 23:29:54 +000010971static
10972void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10973 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10974 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10975 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10976 Sema &S) {
10977 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10978 CE = Current.end();
10979 if (Ctor->isInvalidDecl())
10980 return;
10981
10982 const FunctionDecl *FNTarget = 0;
10983 CXXConstructorDecl *Target;
10984
10985 // We ignore the result here since if we don't have a body, Target will be
10986 // null below.
10987 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10988 Target
10989= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10990
10991 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10992 // Avoid dereferencing a null pointer here.
10993 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10994
10995 if (!Current.insert(Canonical))
10996 return;
10997
10998 // We know that beyond here, we aren't chaining into a cycle.
10999 if (!Target || !Target->isDelegatingConstructor() ||
11000 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11001 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11002 Valid.insert(*CI);
11003 Current.clear();
11004 // We've hit a cycle.
11005 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11006 Current.count(TCanonical)) {
11007 // If we haven't diagnosed this cycle yet, do so now.
11008 if (!Invalid.count(TCanonical)) {
11009 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011010 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011011 << Ctor;
11012
11013 // Don't add a note for a function delegating directo to itself.
11014 if (TCanonical != Canonical)
11015 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11016
11017 CXXConstructorDecl *C = Target;
11018 while (C->getCanonicalDecl() != Canonical) {
11019 (void)C->getTargetConstructor()->hasBody(FNTarget);
11020 assert(FNTarget && "Ctor cycle through bodiless function");
11021
11022 C
11023 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11024 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11025 }
11026 }
11027
11028 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11029 Invalid.insert(*CI);
11030 Current.clear();
11031 } else {
11032 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11033 }
11034}
11035
11036
Sean Huntfe57eef2011-05-04 05:57:24 +000011037void Sema::CheckDelegatingCtorCycles() {
11038 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11039
Sean Huntebcbe1d2011-05-04 23:29:54 +000011040 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11041 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011042
Douglas Gregor0129b562011-07-27 21:57:17 +000011043 for (DelegatingCtorDeclsType::iterator
11044 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011045 E = DelegatingCtorDecls.end();
11046 I != E; ++I) {
11047 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011048 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011049
11050 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11051 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011052}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011053
11054/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11055Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11056 // Implicitly declared functions (e.g. copy constructors) are
11057 // __host__ __device__
11058 if (D->isImplicit())
11059 return CFT_HostDevice;
11060
11061 if (D->hasAttr<CUDAGlobalAttr>())
11062 return CFT_Global;
11063
11064 if (D->hasAttr<CUDADeviceAttr>()) {
11065 if (D->hasAttr<CUDAHostAttr>())
11066 return CFT_HostDevice;
11067 else
11068 return CFT_Device;
11069 }
11070
11071 return CFT_Host;
11072}
11073
11074bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11075 CUDAFunctionTarget CalleeTarget) {
11076 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11077 // Callable from the device only."
11078 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11079 return true;
11080
11081 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11082 // Callable from the host only."
11083 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11084 // Callable from the host only."
11085 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11086 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11087 return true;
11088
11089 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11090 return true;
11091
11092 return false;
11093}