blob: f21d7664e5e0e6147add9c027c96e3b578e7cb18 [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.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 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//
651// This implements C++0x [dcl.constexpr]p3,4, as amended by N3308.
652//
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
662 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(NewFD)) {
663 // C++0x [dcl.constexpr]p4:
664 // In the definition of a constexpr constructor, each of the parameter
665 // types shall be a literal type.
666 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
667 return false;
668
669 // In addition, either its function-body shall be = delete or = default or
670 // it shall satisfy the following constraints:
671 // - the class shall not have any virtual base classes;
672 const CXXRecordDecl *RD = CD->getParent();
673 if (RD->getNumVBases()) {
674 // Note, this is still illegal if the body is = default, since the
675 // implicit body does not satisfy the requirements of a constexpr
676 // constructor. We also reject cases where the body is = delete, as
677 // required by N3308.
678 if (CCK != CCK_Instantiation) {
679 Diag(NewFD->getLocation(),
680 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
681 : diag::note_constexpr_tmpl_virtual_base)
682 << RD->isStruct() << RD->getNumVBases();
683 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 }
690 } else {
691 // C++0x [dcl.constexpr]p3:
692 // The definition of a constexpr function shall satisfy the following
693 // constraints:
694 // - it shall not be virtual;
695 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
696 if (Method && Method->isVirtual()) {
697 if (CCK != CCK_Instantiation) {
698 Diag(NewFD->getLocation(),
699 CCK == CCK_Declaration ? diag::err_constexpr_virtual
700 : diag::note_constexpr_tmpl_virtual);
701
702 // If it's not obvious why this function is virtual, find an overridden
703 // function which uses the 'virtual' keyword.
704 const CXXMethodDecl *WrittenVirtual = Method;
705 while (!WrittenVirtual->isVirtualAsWritten())
706 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
707 if (WrittenVirtual != Method)
708 Diag(WrittenVirtual->getLocation(),
709 diag::note_overridden_virtual_function);
710 }
711 return false;
712 }
713
714 // - its return type shall be a literal type;
715 QualType RT = NewFD->getResultType();
716 if (!RT->isDependentType() &&
717 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
718 PDiag(diag::err_constexpr_non_literal_return) :
719 PDiag(),
720 /*AllowIncompleteType*/ true)) {
721 if (CCK == CCK_NoteNonConstexprInstantiation)
722 Diag(NewFD->getLocation(),
723 diag::note_constexpr_tmpl_non_literal_return) << RT;
724 return false;
725 }
726
727 // - each of its parameter types shall be a literal type;
728 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
729 return false;
730 }
731
732 return true;
733}
734
735/// Check the given declaration statement is legal within a constexpr function
736/// body. C++0x [dcl.constexpr]p3,p4.
737///
738/// \return true if the body is OK, false if we have diagnosed a problem.
739static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
740 DeclStmt *DS) {
741 // C++0x [dcl.constexpr]p3 and p4:
742 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
743 // contain only
744 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
745 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
746 switch ((*DclIt)->getKind()) {
747 case Decl::StaticAssert:
748 case Decl::Using:
749 case Decl::UsingShadow:
750 case Decl::UsingDirective:
751 case Decl::UnresolvedUsingTypename:
752 // - static_assert-declarations
753 // - using-declarations,
754 // - using-directives,
755 continue;
756
757 case Decl::Typedef:
758 case Decl::TypeAlias: {
759 // - typedef declarations and alias-declarations that do not define
760 // classes or enumerations,
761 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
762 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
763 // Don't allow variably-modified types in constexpr functions.
764 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
765 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
766 << TL.getSourceRange() << TL.getType()
767 << isa<CXXConstructorDecl>(Dcl);
768 return false;
769 }
770 continue;
771 }
772
773 case Decl::Enum:
774 case Decl::CXXRecord:
775 // As an extension, we allow the declaration (but not the definition) of
776 // classes and enumerations in all declarations, not just in typedef and
777 // alias declarations.
778 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
779 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
780 << isa<CXXConstructorDecl>(Dcl);
781 return false;
782 }
783 continue;
784
785 case Decl::Var:
786 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
787 << isa<CXXConstructorDecl>(Dcl);
788 return false;
789
790 default:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794 }
795 }
796
797 return true;
798}
799
800/// Check that the given field is initialized within a constexpr constructor.
801///
802/// \param Dcl The constexpr constructor being checked.
803/// \param Field The field being checked. This may be a member of an anonymous
804/// struct or union nested within the class being checked.
805/// \param Inits All declarations, including anonymous struct/union members and
806/// indirect members, for which any initialization was provided.
807/// \param Diagnosed Set to true if an error is produced.
808static void CheckConstexprCtorInitializer(Sema &SemaRef,
809 const FunctionDecl *Dcl,
810 FieldDecl *Field,
811 llvm::SmallSet<Decl*, 16> &Inits,
812 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000813 if (Field->isUnnamedBitfield())
814 return;
815
Richard Smith9f569cc2011-10-01 02:31:28 +0000816 if (!Inits.count(Field)) {
817 if (!Diagnosed) {
818 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
819 Diagnosed = true;
820 }
821 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
822 } else if (Field->isAnonymousStructOrUnion()) {
823 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
824 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
825 I != E; ++I)
826 // If an anonymous union contains an anonymous struct of which any member
827 // is initialized, all members must be initialized.
828 if (!RD->isUnion() || Inits.count(*I))
829 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
830 }
831}
832
833/// Check the body for the given constexpr function declaration only contains
834/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
835///
836/// \return true if the body is OK, false if we have diagnosed a problem.
837bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
838 if (isa<CXXTryStmt>(Body)) {
839 // C++0x [dcl.constexpr]p3:
840 // The definition of a constexpr function shall satisfy the following
841 // constraints: [...]
842 // - its function-body shall be = delete, = default, or a
843 // compound-statement
844 //
845 // C++0x [dcl.constexpr]p4:
846 // In the definition of a constexpr constructor, [...]
847 // - its function-body shall not be a function-try-block;
848 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
849 << isa<CXXConstructorDecl>(Dcl);
850 return false;
851 }
852
853 // - its function-body shall be [...] a compound-statement that contains only
854 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
855
856 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
857 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
858 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
859 switch ((*BodyIt)->getStmtClass()) {
860 case Stmt::NullStmtClass:
861 // - null statements,
862 continue;
863
864 case Stmt::DeclStmtClass:
865 // - static_assert-declarations
866 // - using-declarations,
867 // - using-directives,
868 // - typedef declarations and alias-declarations that do not define
869 // classes or enumerations,
870 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
871 return false;
872 continue;
873
874 case Stmt::ReturnStmtClass:
875 // - and exactly one return statement;
876 if (isa<CXXConstructorDecl>(Dcl))
877 break;
878
879 ReturnStmts.push_back((*BodyIt)->getLocStart());
880 // FIXME
881 // - every constructor call and implicit conversion used in initializing
882 // the return value shall be one of those allowed in a constant
883 // expression.
884 // Deal with this as part of a general check that the function can produce
885 // a constant expression (for [dcl.constexpr]p5).
886 continue;
887
888 default:
889 break;
890 }
891
892 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
893 << isa<CXXConstructorDecl>(Dcl);
894 return false;
895 }
896
897 if (const CXXConstructorDecl *Constructor
898 = dyn_cast<CXXConstructorDecl>(Dcl)) {
899 const CXXRecordDecl *RD = Constructor->getParent();
900 // - every non-static data member and base class sub-object shall be
901 // initialized;
902 if (RD->isUnion()) {
903 // DR1359: Exactly one member of a union shall be initialized.
904 if (Constructor->getNumCtorInitializers() == 0) {
905 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
906 return false;
907 }
Richard Smith6e433752011-10-10 16:38:04 +0000908 } else if (!Constructor->isDependentContext() &&
909 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
911
912 // Skip detailed checking if we have enough initializers, and we would
913 // allow at most one initializer per member.
914 bool AnyAnonStructUnionMembers = false;
915 unsigned Fields = 0;
916 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
917 E = RD->field_end(); I != E; ++I, ++Fields) {
918 if ((*I)->isAnonymousStructOrUnion()) {
919 AnyAnonStructUnionMembers = true;
920 break;
921 }
922 }
923 if (AnyAnonStructUnionMembers ||
924 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
925 // Check initialization of non-static data members. Base classes are
926 // always initialized so do not need to be checked. Dependent bases
927 // might not have initializers in the member initializer list.
928 llvm::SmallSet<Decl*, 16> Inits;
929 for (CXXConstructorDecl::init_const_iterator
930 I = Constructor->init_begin(), E = Constructor->init_end();
931 I != E; ++I) {
932 if (FieldDecl *FD = (*I)->getMember())
933 Inits.insert(FD);
934 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
935 Inits.insert(ID->chain_begin(), ID->chain_end());
936 }
937
938 bool Diagnosed = false;
939 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
940 E = RD->field_end(); I != E; ++I)
941 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
942 if (Diagnosed)
943 return false;
944 }
945 }
946
947 // FIXME
948 // - every constructor involved in initializing non-static data members
949 // and base class sub-objects shall be a constexpr constructor;
950 // - every assignment-expression that is an initializer-clause appearing
951 // directly or indirectly within a brace-or-equal-initializer for
952 // a non-static data member that is not named by a mem-initializer-id
953 // shall be a constant expression; and
954 // - every implicit conversion used in converting a constructor argument
955 // to the corresponding parameter type and converting
956 // a full-expression to the corresponding member type shall be one of
957 // those allowed in a constant expression.
958 // Deal with these as part of a general check that the function can produce
959 // a constant expression (for [dcl.constexpr]p5).
960 } else {
961 if (ReturnStmts.empty()) {
962 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
963 return false;
964 }
965 if (ReturnStmts.size() > 1) {
966 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
967 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
968 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
969 return false;
970 }
971 }
972
973 return true;
974}
975
Douglas Gregorb48fe382008-10-31 09:07:45 +0000976/// isCurrentClassName - Determine whether the identifier II is the
977/// name of the class type currently being defined. In the case of
978/// nested classes, this will only return true if II is the name of
979/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000980bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
981 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000982 assert(getLangOptions().CPlusPlus && "No class names in C!");
983
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000984 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000985 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000986 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000987 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
988 } else
989 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
990
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000991 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000992 return &II == CurDecl->getIdentifier();
993 else
994 return false;
995}
996
Mike Stump1eb44332009-09-09 15:08:12 +0000997/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000998///
999/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1000/// and returns NULL otherwise.
1001CXXBaseSpecifier *
1002Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1003 SourceRange SpecifierRange,
1004 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001005 TypeSourceInfo *TInfo,
1006 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001007 QualType BaseType = TInfo->getType();
1008
Douglas Gregor2943aed2009-03-03 04:44:36 +00001009 // C++ [class.union]p1:
1010 // A union shall not have base classes.
1011 if (Class->isUnion()) {
1012 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1013 << SpecifierRange;
1014 return 0;
1015 }
1016
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001017 if (EllipsisLoc.isValid() &&
1018 !TInfo->getType()->containsUnexpandedParameterPack()) {
1019 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1020 << TInfo->getTypeLoc().getSourceRange();
1021 EllipsisLoc = SourceLocation();
1022 }
1023
Douglas Gregor2943aed2009-03-03 04:44:36 +00001024 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001025 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001026 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001027 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001028
1029 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001030
1031 // Base specifiers must be record types.
1032 if (!BaseType->isRecordType()) {
1033 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1034 return 0;
1035 }
1036
1037 // C++ [class.union]p1:
1038 // A union shall not be used as a base class.
1039 if (BaseType->isUnionType()) {
1040 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1041 return 0;
1042 }
1043
1044 // C++ [class.derived]p2:
1045 // The class-name in a base-specifier shall not be an incompletely
1046 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001047 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001048 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001049 << SpecifierRange)) {
1050 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001051 return 0;
John McCall572fc622010-08-17 07:23:57 +00001052 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001053
Eli Friedman1d954f62009-08-15 21:55:26 +00001054 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001055 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001056 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001057 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001058 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001059 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1060 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001061
Anders Carlsson1d209272011-03-25 14:55:14 +00001062 // C++ [class]p3:
1063 // If a class is marked final and it appears as a base-type-specifier in
1064 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001065 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001066 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1067 << CXXBaseDecl->getDeclName();
1068 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1069 << CXXBaseDecl->getDeclName();
1070 return 0;
1071 }
1072
John McCall572fc622010-08-17 07:23:57 +00001073 if (BaseDecl->isInvalidDecl())
1074 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001075
1076 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001077 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001078 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001079 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001080}
1081
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001082/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1083/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001084/// example:
1085/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001086/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001087BaseResult
John McCalld226f652010-08-21 09:40:31 +00001088Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001089 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001090 ParsedType basetype, SourceLocation BaseLoc,
1091 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001092 if (!classdecl)
1093 return true;
1094
Douglas Gregor40808ce2009-03-09 23:48:35 +00001095 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001096 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001097 if (!Class)
1098 return true;
1099
Nick Lewycky56062202010-07-26 16:56:01 +00001100 TypeSourceInfo *TInfo = 0;
1101 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001102
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001103 if (EllipsisLoc.isInvalid() &&
1104 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001105 UPPC_BaseType))
1106 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001107
Douglas Gregor2943aed2009-03-03 04:44:36 +00001108 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001109 Virtual, Access, TInfo,
1110 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001111 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Douglas Gregor2943aed2009-03-03 04:44:36 +00001113 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001114}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001115
Douglas Gregor2943aed2009-03-03 04:44:36 +00001116/// \brief Performs the actual work of attaching the given base class
1117/// specifiers to a C++ class.
1118bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1119 unsigned NumBases) {
1120 if (NumBases == 0)
1121 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001122
1123 // Used to keep track of which base types we have already seen, so
1124 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001125 // that the key is always the unqualified canonical type of the base
1126 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001127 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1128
1129 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001130 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001131 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001132 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001133 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001134 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001135 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001136 if (KnownBaseTypes[NewBaseType]) {
1137 // C++ [class.mi]p3:
1138 // A class shall not be specified as a direct base class of a
1139 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001140 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001141 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001142 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001143 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001144
1145 // Delete the duplicate base class specifier; we're going to
1146 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001147 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001148
1149 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001150 } else {
1151 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001152 KnownBaseTypes[NewBaseType] = Bases[idx];
1153 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001154 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001155 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1156 if (RD->hasAttr<WeakAttr>())
1157 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001158 }
1159 }
1160
1161 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001162 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001163
1164 // Delete the remaining (good) base class specifiers, since their
1165 // data has been copied into the CXXRecordDecl.
1166 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001167 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001168
1169 return Invalid;
1170}
1171
1172/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1173/// class, after checking whether there are any duplicate base
1174/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001175void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001176 unsigned NumBases) {
1177 if (!ClassDecl || !Bases || !NumBases)
1178 return;
1179
1180 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001181 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001182 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001183}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001184
John McCall3cb0ebd2010-03-10 03:28:59 +00001185static CXXRecordDecl *GetClassForType(QualType T) {
1186 if (const RecordType *RT = T->getAs<RecordType>())
1187 return cast<CXXRecordDecl>(RT->getDecl());
1188 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1189 return ICT->getDecl();
1190 else
1191 return 0;
1192}
1193
Douglas Gregora8f32e02009-10-06 17:59:45 +00001194/// \brief Determine whether the type \p Derived is a C++ class that is
1195/// derived from the type \p Base.
1196bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1197 if (!getLangOptions().CPlusPlus)
1198 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001199
1200 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1201 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001202 return false;
1203
John McCall3cb0ebd2010-03-10 03:28:59 +00001204 CXXRecordDecl *BaseRD = GetClassForType(Base);
1205 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001206 return false;
1207
John McCall86ff3082010-02-04 22:26:26 +00001208 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1209 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001210}
1211
1212/// \brief Determine whether the type \p Derived is a C++ class that is
1213/// derived from the type \p Base.
1214bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1215 if (!getLangOptions().CPlusPlus)
1216 return false;
1217
John McCall3cb0ebd2010-03-10 03:28:59 +00001218 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1219 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001220 return false;
1221
John McCall3cb0ebd2010-03-10 03:28:59 +00001222 CXXRecordDecl *BaseRD = GetClassForType(Base);
1223 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001224 return false;
1225
Douglas Gregora8f32e02009-10-06 17:59:45 +00001226 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1227}
1228
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001229void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001230 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001231 assert(BasePathArray.empty() && "Base path array must be empty!");
1232 assert(Paths.isRecordingPaths() && "Must record paths!");
1233
1234 const CXXBasePath &Path = Paths.front();
1235
1236 // We first go backward and check if we have a virtual base.
1237 // FIXME: It would be better if CXXBasePath had the base specifier for
1238 // the nearest virtual base.
1239 unsigned Start = 0;
1240 for (unsigned I = Path.size(); I != 0; --I) {
1241 if (Path[I - 1].Base->isVirtual()) {
1242 Start = I - 1;
1243 break;
1244 }
1245 }
1246
1247 // Now add all bases.
1248 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001249 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001250}
1251
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001252/// \brief Determine whether the given base path includes a virtual
1253/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001254bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1255 for (CXXCastPath::const_iterator B = BasePath.begin(),
1256 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001257 B != BEnd; ++B)
1258 if ((*B)->isVirtual())
1259 return true;
1260
1261 return false;
1262}
1263
Douglas Gregora8f32e02009-10-06 17:59:45 +00001264/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1265/// conversion (where Derived and Base are class types) is
1266/// well-formed, meaning that the conversion is unambiguous (and
1267/// that all of the base classes are accessible). Returns true
1268/// and emits a diagnostic if the code is ill-formed, returns false
1269/// otherwise. Loc is the location where this routine should point to
1270/// if there is an error, and Range is the source range to highlight
1271/// if there is an error.
1272bool
1273Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001274 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001275 unsigned AmbigiousBaseConvID,
1276 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001277 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001278 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001279 // First, determine whether the path from Derived to Base is
1280 // ambiguous. This is slightly more expensive than checking whether
1281 // the Derived to Base conversion exists, because here we need to
1282 // explore multiple paths to determine if there is an ambiguity.
1283 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1284 /*DetectVirtual=*/false);
1285 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1286 assert(DerivationOkay &&
1287 "Can only be used with a derived-to-base conversion");
1288 (void)DerivationOkay;
1289
1290 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001291 if (InaccessibleBaseID) {
1292 // Check that the base class can be accessed.
1293 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1294 InaccessibleBaseID)) {
1295 case AR_inaccessible:
1296 return true;
1297 case AR_accessible:
1298 case AR_dependent:
1299 case AR_delayed:
1300 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001301 }
John McCall6b2accb2010-02-10 09:31:12 +00001302 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001303
1304 // Build a base path if necessary.
1305 if (BasePath)
1306 BuildBasePathArray(Paths, *BasePath);
1307 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001308 }
1309
1310 // We know that the derived-to-base conversion is ambiguous, and
1311 // we're going to produce a diagnostic. Perform the derived-to-base
1312 // search just one more time to compute all of the possible paths so
1313 // that we can print them out. This is more expensive than any of
1314 // the previous derived-to-base checks we've done, but at this point
1315 // performance isn't as much of an issue.
1316 Paths.clear();
1317 Paths.setRecordingPaths(true);
1318 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1319 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1320 (void)StillOkay;
1321
1322 // Build up a textual representation of the ambiguous paths, e.g.,
1323 // D -> B -> A, that will be used to illustrate the ambiguous
1324 // conversions in the diagnostic. We only print one of the paths
1325 // to each base class subobject.
1326 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1327
1328 Diag(Loc, AmbigiousBaseConvID)
1329 << Derived << Base << PathDisplayStr << Range << Name;
1330 return true;
1331}
1332
1333bool
1334Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001335 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001336 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001337 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001338 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001339 IgnoreAccess ? 0
1340 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001341 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001342 Loc, Range, DeclarationName(),
1343 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001344}
1345
1346
1347/// @brief Builds a string representing ambiguous paths from a
1348/// specific derived class to different subobjects of the same base
1349/// class.
1350///
1351/// This function builds a string that can be used in error messages
1352/// to show the different paths that one can take through the
1353/// inheritance hierarchy to go from the derived class to different
1354/// subobjects of a base class. The result looks something like this:
1355/// @code
1356/// struct D -> struct B -> struct A
1357/// struct D -> struct C -> struct A
1358/// @endcode
1359std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1360 std::string PathDisplayStr;
1361 std::set<unsigned> DisplayedPaths;
1362 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1363 Path != Paths.end(); ++Path) {
1364 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1365 // We haven't displayed a path to this particular base
1366 // class subobject yet.
1367 PathDisplayStr += "\n ";
1368 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1369 for (CXXBasePath::const_iterator Element = Path->begin();
1370 Element != Path->end(); ++Element)
1371 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1372 }
1373 }
1374
1375 return PathDisplayStr;
1376}
1377
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001378//===----------------------------------------------------------------------===//
1379// C++ class member Handling
1380//===----------------------------------------------------------------------===//
1381
Abramo Bagnara6206d532010-06-05 05:09:32 +00001382/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001383bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1384 SourceLocation ASLoc,
1385 SourceLocation ColonLoc,
1386 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001387 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001388 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001389 ASLoc, ColonLoc);
1390 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001391 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001392}
1393
Anders Carlsson9e682d92011-01-20 05:57:14 +00001394/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001395void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001396 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001397 if (!MD || !MD->isVirtual())
1398 return;
1399
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001400 if (MD->isDependentContext())
1401 return;
1402
Anders Carlsson9e682d92011-01-20 05:57:14 +00001403 // C++0x [class.virtual]p3:
1404 // If a virtual function is marked with the virt-specifier override and does
1405 // not override a member function of a base class,
1406 // the program is ill-formed.
1407 bool HasOverriddenMethods =
1408 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001409 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001410 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001411 diag::err_function_marked_override_not_overriding)
1412 << MD->getDeclName();
1413 return;
1414 }
1415}
1416
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001417/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1418/// function overrides a virtual member function marked 'final', according to
1419/// C++0x [class.virtual]p3.
1420bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1421 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001422 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001423 return false;
1424
1425 Diag(New->getLocation(), diag::err_final_function_overridden)
1426 << New->getDeclName();
1427 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1428 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001429}
1430
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001431/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1432/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001433/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1434/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1435/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001436Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001437Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001438 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001439 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001440 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001441 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001442 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1443 DeclarationName Name = NameInfo.getName();
1444 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001445
1446 // For anonymous bitfields, the location should point to the type.
1447 if (Loc.isInvalid())
1448 Loc = D.getSourceRange().getBegin();
1449
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001450 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001451
John McCall4bde1e12010-06-04 08:34:12 +00001452 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001453 assert(!DS.isFriendSpecified());
1454
Richard Smith1ab0d902011-06-25 02:28:38 +00001455 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001456
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001457 // C++ 9.2p6: A member shall not be declared to have automatic storage
1458 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001459 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1460 // data members and cannot be applied to names declared const or static,
1461 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001462 switch (DS.getStorageClassSpec()) {
1463 case DeclSpec::SCS_unspecified:
1464 case DeclSpec::SCS_typedef:
1465 case DeclSpec::SCS_static:
1466 // FALL THROUGH.
1467 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001468 case DeclSpec::SCS_mutable:
1469 if (isFunc) {
1470 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001471 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001472 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001473 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Sebastian Redla11f42f2008-11-17 23:24:37 +00001475 // FIXME: It would be nicer if the keyword was ignored only for this
1476 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001477 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001478 }
1479 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001480 default:
1481 if (DS.getStorageClassSpecLoc().isValid())
1482 Diag(DS.getStorageClassSpecLoc(),
1483 diag::err_storageclass_invalid_for_member);
1484 else
1485 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1486 D.getMutableDeclSpec().ClearStorageClassSpecs();
1487 }
1488
Sebastian Redl669d5d72008-11-14 23:42:31 +00001489 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1490 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001491 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001492
1493 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001494 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001495 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001496
1497 // Data members must have identifiers for names.
1498 if (Name.getNameKind() != DeclarationName::Identifier) {
1499 Diag(Loc, diag::err_bad_variable_name)
1500 << Name;
1501 return 0;
1502 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001503
Douglas Gregorf2503652011-09-21 14:40:46 +00001504 IdentifierInfo *II = Name.getAsIdentifierInfo();
1505
1506 // Member field could not be with "template" keyword.
1507 // So TemplateParameterLists should be empty in this case.
1508 if (TemplateParameterLists.size()) {
1509 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1510 if (TemplateParams->size()) {
1511 // There is no such thing as a member field template.
1512 Diag(D.getIdentifierLoc(), diag::err_template_member)
1513 << II
1514 << SourceRange(TemplateParams->getTemplateLoc(),
1515 TemplateParams->getRAngleLoc());
1516 } else {
1517 // There is an extraneous 'template<>' for this member.
1518 Diag(TemplateParams->getTemplateLoc(),
1519 diag::err_template_member_noparams)
1520 << II
1521 << SourceRange(TemplateParams->getTemplateLoc(),
1522 TemplateParams->getRAngleLoc());
1523 }
1524 return 0;
1525 }
1526
Douglas Gregor922fff22010-10-13 22:19:53 +00001527 if (SS.isSet() && !SS.isInvalid()) {
1528 // The user provided a superfluous scope specifier inside a class
1529 // definition:
1530 //
1531 // class X {
1532 // int X::member;
1533 // };
1534 DeclContext *DC = 0;
1535 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1536 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001537 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001538 else
1539 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1540 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001541
Douglas Gregor922fff22010-10-13 22:19:53 +00001542 SS.clear();
1543 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001544
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001545 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001546 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001547 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001548 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001549 assert(!HasDeferredInit);
1550
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001551 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001552 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001553 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001554 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001555
1556 // Non-instance-fields can't have a bitfield.
1557 if (BitWidth) {
1558 if (Member->isInvalidDecl()) {
1559 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001560 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001561 // C++ 9.6p3: A bit-field shall not be a static member.
1562 // "static member 'A' cannot be a bit-field"
1563 Diag(Loc, diag::err_static_not_bitfield)
1564 << Name << BitWidth->getSourceRange();
1565 } else if (isa<TypedefDecl>(Member)) {
1566 // "typedef member 'x' cannot be a bit-field"
1567 Diag(Loc, diag::err_typedef_not_bitfield)
1568 << Name << BitWidth->getSourceRange();
1569 } else {
1570 // A function typedef ("typedef int f(); f a;").
1571 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1572 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001573 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001574 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Chris Lattner8b963ef2009-03-05 23:01:03 +00001577 BitWidth = 0;
1578 Member->setInvalidDecl();
1579 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001580
1581 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Douglas Gregor37b372b2009-08-20 22:52:58 +00001583 // If we have declared a member function template, set the access of the
1584 // templated declaration as well.
1585 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1586 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001587 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001588
Anders Carlssonaae5af22011-01-20 04:34:22 +00001589 if (VS.isOverrideSpecified()) {
1590 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1591 if (!MD || !MD->isVirtual()) {
1592 Diag(Member->getLocStart(),
1593 diag::override_keyword_only_allowed_on_virtual_member_functions)
1594 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001595 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001596 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001597 }
1598 if (VS.isFinalSpecified()) {
1599 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1600 if (!MD || !MD->isVirtual()) {
1601 Diag(Member->getLocStart(),
1602 diag::override_keyword_only_allowed_on_virtual_member_functions)
1603 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001604 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001605 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001606 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001607
Douglas Gregorf5251602011-03-08 17:10:18 +00001608 if (VS.getLastLocation().isValid()) {
1609 // Update the end location of a method that has a virt-specifiers.
1610 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1611 MD->setRangeEnd(VS.getLastLocation());
1612 }
1613
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001614 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001615
Douglas Gregor10bd3682008-11-17 22:58:34 +00001616 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001617
John McCallb25b2952011-02-15 07:12:36 +00001618 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001619 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001620 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001621}
1622
Richard Smith7a614d82011-06-11 17:19:42 +00001623/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001624/// in-class initializer for a non-static C++ class member, and after
1625/// instantiating an in-class initializer in a class template. Such actions
1626/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001627void
1628Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1629 Expr *InitExpr) {
1630 FieldDecl *FD = cast<FieldDecl>(D);
1631
1632 if (!InitExpr) {
1633 FD->setInvalidDecl();
1634 FD->removeInClassInitializer();
1635 return;
1636 }
1637
Peter Collingbournefef21892011-10-23 18:59:44 +00001638 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1639 FD->setInvalidDecl();
1640 FD->removeInClassInitializer();
1641 return;
1642 }
1643
Richard Smith7a614d82011-06-11 17:19:42 +00001644 ExprResult Init = InitExpr;
1645 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1646 // FIXME: if there is no EqualLoc, this is list-initialization.
1647 Init = PerformCopyInitialization(
1648 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1649 if (Init.isInvalid()) {
1650 FD->setInvalidDecl();
1651 return;
1652 }
1653
1654 CheckImplicitConversions(Init.get(), EqualLoc);
1655 }
1656
1657 // C++0x [class.base.init]p7:
1658 // The initialization of each base and member constitutes a
1659 // full-expression.
1660 Init = MaybeCreateExprWithCleanups(Init);
1661 if (Init.isInvalid()) {
1662 FD->setInvalidDecl();
1663 return;
1664 }
1665
1666 InitExpr = Init.release();
1667
1668 FD->setInClassInitializer(InitExpr);
1669}
1670
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001671/// \brief Find the direct and/or virtual base specifiers that
1672/// correspond to the given base type, for use in base initialization
1673/// within a constructor.
1674static bool FindBaseInitializer(Sema &SemaRef,
1675 CXXRecordDecl *ClassDecl,
1676 QualType BaseType,
1677 const CXXBaseSpecifier *&DirectBaseSpec,
1678 const CXXBaseSpecifier *&VirtualBaseSpec) {
1679 // First, check for a direct base class.
1680 DirectBaseSpec = 0;
1681 for (CXXRecordDecl::base_class_const_iterator Base
1682 = ClassDecl->bases_begin();
1683 Base != ClassDecl->bases_end(); ++Base) {
1684 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1685 // We found a direct base of this type. That's what we're
1686 // initializing.
1687 DirectBaseSpec = &*Base;
1688 break;
1689 }
1690 }
1691
1692 // Check for a virtual base class.
1693 // FIXME: We might be able to short-circuit this if we know in advance that
1694 // there are no virtual bases.
1695 VirtualBaseSpec = 0;
1696 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1697 // We haven't found a base yet; search the class hierarchy for a
1698 // virtual base class.
1699 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1700 /*DetectVirtual=*/false);
1701 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1702 BaseType, Paths)) {
1703 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1704 Path != Paths.end(); ++Path) {
1705 if (Path->back().Base->isVirtual()) {
1706 VirtualBaseSpec = Path->back().Base;
1707 break;
1708 }
1709 }
1710 }
1711 }
1712
1713 return DirectBaseSpec || VirtualBaseSpec;
1714}
1715
Sebastian Redl6df65482011-09-24 17:48:25 +00001716/// \brief Handle a C++ member initializer using braced-init-list syntax.
1717MemInitResult
1718Sema::ActOnMemInitializer(Decl *ConstructorD,
1719 Scope *S,
1720 CXXScopeSpec &SS,
1721 IdentifierInfo *MemberOrBase,
1722 ParsedType TemplateTypeTy,
1723 SourceLocation IdLoc,
1724 Expr *InitList,
1725 SourceLocation EllipsisLoc) {
1726 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1727 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1728}
1729
1730/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001731MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001732Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001733 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001734 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001735 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001736 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001737 SourceLocation IdLoc,
1738 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001739 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001740 SourceLocation RParenLoc,
1741 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001742 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1743 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1744 RParenLoc),
1745 EllipsisLoc);
1746}
1747
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001748namespace {
1749
1750// Callback to only accept typo corrections that are namespaces.
1751class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1752 public:
1753 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1754 : ClassDecl(ClassDecl) {}
1755
1756 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1757 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1758 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1759 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1760 else
1761 return isa<TypeDecl>(ND);
1762 }
1763 return false;
1764 }
1765
1766 private:
1767 CXXRecordDecl *ClassDecl;
1768};
1769
1770}
1771
Sebastian Redl6df65482011-09-24 17:48:25 +00001772/// \brief Handle a C++ member initializer.
1773MemInitResult
1774Sema::BuildMemInitializer(Decl *ConstructorD,
1775 Scope *S,
1776 CXXScopeSpec &SS,
1777 IdentifierInfo *MemberOrBase,
1778 ParsedType TemplateTypeTy,
1779 SourceLocation IdLoc,
1780 const MultiInitializer &Args,
1781 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001782 if (!ConstructorD)
1783 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001785 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
1787 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001788 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001789 if (!Constructor) {
1790 // The user wrote a constructor initializer on a function that is
1791 // not a C++ constructor. Ignore the error for now, because we may
1792 // have more member initializers coming; we'll diagnose it just
1793 // once in ActOnMemInitializers.
1794 return true;
1795 }
1796
1797 CXXRecordDecl *ClassDecl = Constructor->getParent();
1798
1799 // C++ [class.base.init]p2:
1800 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001801 // constructor's class and, if not found in that scope, are looked
1802 // up in the scope containing the constructor's definition.
1803 // [Note: if the constructor's class contains a member with the
1804 // same name as a direct or virtual base class of the class, a
1805 // mem-initializer-id naming the member or base class and composed
1806 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001807 // mem-initializer-id for the hidden base class may be specified
1808 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001809 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001810 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001811 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001812 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001813 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001814 ValueDecl *Member;
1815 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1816 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001817 if (EllipsisLoc.isValid())
1818 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001819 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1820
1821 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001822 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001823 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001824 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001825 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001826 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001827 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001828
1829 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001830 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001831 } else {
1832 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1833 LookupParsedName(R, S, &SS);
1834
1835 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1836 if (!TyD) {
1837 if (R.isAmbiguous()) return true;
1838
John McCallfd225442010-04-09 19:01:14 +00001839 // We don't want access-control diagnostics here.
1840 R.suppressDiagnostics();
1841
Douglas Gregor7a886e12010-01-19 06:46:48 +00001842 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1843 bool NotUnknownSpecialization = false;
1844 DeclContext *DC = computeDeclContext(SS, false);
1845 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1846 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1847
1848 if (!NotUnknownSpecialization) {
1849 // When the scope specifier can refer to a member of an unknown
1850 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001851 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1852 SS.getWithLocInContext(Context),
1853 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001854 if (BaseType.isNull())
1855 return true;
1856
Douglas Gregor7a886e12010-01-19 06:46:48 +00001857 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001858 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001859 }
1860 }
1861
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001862 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001863 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001864 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001865 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001866 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001867 &Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001868 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1869 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1870 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001871 // We have found a non-static data member with a similar
1872 // name to what was typed; complain and initialize that
1873 // member.
1874 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1875 << MemberOrBase << true << CorrectedQuotedStr
1876 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1877 Diag(Member->getLocation(), diag::note_previous_decl)
1878 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001879
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001880 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001881 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001882 const CXXBaseSpecifier *DirectBaseSpec;
1883 const CXXBaseSpecifier *VirtualBaseSpec;
1884 if (FindBaseInitializer(*this, ClassDecl,
1885 Context.getTypeDeclType(Type),
1886 DirectBaseSpec, VirtualBaseSpec)) {
1887 // We have found a direct or virtual base class with a
1888 // similar name to what was typed; complain and initialize
1889 // that base class.
1890 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001891 << MemberOrBase << false << CorrectedQuotedStr
1892 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001893
1894 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1895 : VirtualBaseSpec;
1896 Diag(BaseSpec->getSourceRange().getBegin(),
1897 diag::note_base_class_specified_here)
1898 << BaseSpec->getType()
1899 << BaseSpec->getSourceRange();
1900
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001901 TyD = Type;
1902 }
1903 }
1904 }
1905
Douglas Gregor7a886e12010-01-19 06:46:48 +00001906 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001907 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001908 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001909 return true;
1910 }
John McCall2b194412009-12-21 10:41:20 +00001911 }
1912
Douglas Gregor7a886e12010-01-19 06:46:48 +00001913 if (BaseType.isNull()) {
1914 BaseType = Context.getTypeDeclType(TyD);
1915 if (SS.isSet()) {
1916 NestedNameSpecifier *Qualifier =
1917 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001918
Douglas Gregor7a886e12010-01-19 06:46:48 +00001919 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001920 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001921 }
John McCall2b194412009-12-21 10:41:20 +00001922 }
1923 }
Mike Stump1eb44332009-09-09 15:08:12 +00001924
John McCalla93c9342009-12-07 02:54:59 +00001925 if (!TInfo)
1926 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001927
Sebastian Redl6df65482011-09-24 17:48:25 +00001928 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001929}
1930
Chandler Carruth81c64772011-09-03 01:14:15 +00001931/// Checks a member initializer expression for cases where reference (or
1932/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001933static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1934 Expr *Init,
1935 SourceLocation IdLoc) {
1936 QualType MemberTy = Member->getType();
1937
1938 // We only handle pointers and references currently.
1939 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1940 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1941 return;
1942
1943 const bool IsPointer = MemberTy->isPointerType();
1944 if (IsPointer) {
1945 if (const UnaryOperator *Op
1946 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1947 // The only case we're worried about with pointers requires taking the
1948 // address.
1949 if (Op->getOpcode() != UO_AddrOf)
1950 return;
1951
1952 Init = Op->getSubExpr();
1953 } else {
1954 // We only handle address-of expression initializers for pointers.
1955 return;
1956 }
1957 }
1958
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001959 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1960 // Taking the address of a temporary will be diagnosed as a hard error.
1961 if (IsPointer)
1962 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001963
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001964 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1965 << Member << Init->getSourceRange();
1966 } else if (const DeclRefExpr *DRE
1967 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1968 // We only warn when referring to a non-reference parameter declaration.
1969 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1970 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001971 return;
1972
1973 S.Diag(Init->getExprLoc(),
1974 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1975 : diag::warn_bind_ref_member_to_parameter)
1976 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001977 } else {
1978 // Other initializers are fine.
1979 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001980 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001981
1982 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1983 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00001984}
1985
John McCallb4190042009-11-04 23:02:40 +00001986/// Checks an initializer expression for use of uninitialized fields, such as
1987/// containing the field that is being initialized. Returns true if there is an
1988/// uninitialized field was used an updates the SourceLocation parameter; false
1989/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001990static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001991 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001992 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001993 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1994
Nick Lewycky43ad1822010-06-15 07:32:55 +00001995 if (isa<CallExpr>(S)) {
1996 // Do not descend into function calls or constructors, as the use
1997 // of an uninitialized field may be valid. One would have to inspect
1998 // the contents of the function/ctor to determine if it is safe or not.
1999 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2000 // may be safe, depending on what the function/ctor does.
2001 return false;
2002 }
2003 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2004 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002005
2006 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2007 // The member expression points to a static data member.
2008 assert(VD->isStaticDataMember() &&
2009 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002010 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002011 return false;
2012 }
2013
2014 if (isa<EnumConstantDecl>(RhsField)) {
2015 // The member expression points to an enum.
2016 return false;
2017 }
2018
John McCallb4190042009-11-04 23:02:40 +00002019 if (RhsField == LhsField) {
2020 // Initializing a field with itself. Throw a warning.
2021 // But wait; there are exceptions!
2022 // Exception #1: The field may not belong to this record.
2023 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002024 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002025 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2026 // Even though the field matches, it does not belong to this record.
2027 return false;
2028 }
2029 // None of the exceptions triggered; return true to indicate an
2030 // uninitialized field was used.
2031 *L = ME->getMemberLoc();
2032 return true;
2033 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002034 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002035 // sizeof/alignof doesn't reference contents, do not warn.
2036 return false;
2037 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2038 // address-of doesn't reference contents (the pointer may be dereferenced
2039 // in the same expression but it would be rare; and weird).
2040 if (UOE->getOpcode() == UO_AddrOf)
2041 return false;
John McCallb4190042009-11-04 23:02:40 +00002042 }
John McCall7502c1d2011-02-13 04:07:26 +00002043 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002044 if (!*it) {
2045 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002046 continue;
2047 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002048 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2049 return true;
John McCallb4190042009-11-04 23:02:40 +00002050 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002051 return false;
John McCallb4190042009-11-04 23:02:40 +00002052}
2053
John McCallf312b1e2010-08-26 23:41:50 +00002054MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002055Sema::BuildMemberInitializer(ValueDecl *Member,
2056 const MultiInitializer &Args,
2057 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002058 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2059 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2060 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002061 "Member must be a FieldDecl or IndirectFieldDecl");
2062
Peter Collingbournefef21892011-10-23 18:59:44 +00002063 if (Args.DiagnoseUnexpandedParameterPack(*this))
2064 return true;
2065
Douglas Gregor464b2f02010-11-05 22:21:31 +00002066 if (Member->isInvalidDecl())
2067 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002068
John McCallb4190042009-11-04 23:02:40 +00002069 // Diagnose value-uses of fields to initialize themselves, e.g.
2070 // foo(foo)
2071 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002072 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002073 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2074 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002075 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002076 Expr *Arg = *I;
2077 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2078 Arg = DIE->getInit();
2079 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002080 // FIXME: Return true in the case when other fields are used before being
2081 // uninitialized. For example, let this field be the i'th field. When
2082 // initializing the i'th field, throw a warning if any of the >= i'th
2083 // fields are used, as they are not yet initialized.
2084 // Right now we are only handling the case where the i'th field uses
2085 // itself in its initializer.
2086 Diag(L, diag::warn_field_is_uninit);
2087 }
2088 }
2089
Sebastian Redl6df65482011-09-24 17:48:25 +00002090 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002091
Chandler Carruth894aed92010-12-06 09:23:57 +00002092 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002093 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002094 // Can't check initialization for a member of dependent type or when
2095 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002096 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002097
John McCallf85e1932011-06-15 23:02:42 +00002098 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002099 } else {
2100 // Initialize the member.
2101 InitializedEntity MemberEntity =
2102 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2103 : InitializedEntity::InitializeMember(IndirectMember, 0);
2104 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002105 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2106 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002107
Sebastian Redl6df65482011-09-24 17:48:25 +00002108 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002109 if (MemberInit.isInvalid())
2110 return true;
2111
Sebastian Redl6df65482011-09-24 17:48:25 +00002112 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002113
2114 // C++0x [class.base.init]p7:
2115 // The initialization of each base and member constitutes a
2116 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002117 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002118 if (MemberInit.isInvalid())
2119 return true;
2120
2121 // If we are in a dependent context, template instantiation will
2122 // perform this type-checking again. Just save the arguments that we
2123 // received in a ParenListExpr.
2124 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2125 // of the information that we have about the member
2126 // initializer. However, deconstructing the ASTs is a dicey process,
2127 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002128 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002129 Init = Args.CreateInitExpr(Context,
2130 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002131 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002132 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002133 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2134 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002135 }
2136
Chandler Carruth894aed92010-12-06 09:23:57 +00002137 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002138 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002139 IdLoc, Args.getStartLoc(),
2140 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002141 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002142 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002143 IdLoc, Args.getStartLoc(),
2144 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002145 }
Eli Friedman59c04372009-07-29 19:44:27 +00002146}
2147
John McCallf312b1e2010-08-26 23:41:50 +00002148MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002149Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002150 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002151 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002152 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002153 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002154 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002155 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002156 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002157
Sean Hunt41717662011-02-26 19:13:13 +00002158 // Initialize the object.
2159 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2160 QualType(ClassDecl->getTypeForDecl(), 0));
2161 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002162 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2163 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002164
Sebastian Redl6df65482011-09-24 17:48:25 +00002165 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002166 if (DelegationInit.isInvalid())
2167 return true;
2168
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002169 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2170 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002171
Sebastian Redl6df65482011-09-24 17:48:25 +00002172 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002173
2174 // C++0x [class.base.init]p7:
2175 // The initialization of each base and member constitutes a
2176 // full-expression.
2177 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2178 if (DelegationInit.isInvalid())
2179 return true;
2180
Douglas Gregor76852c22011-11-01 01:16:03 +00002181 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002182 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002183 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002184}
2185
2186MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002187Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002188 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002189 CXXRecordDecl *ClassDecl,
2190 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002191 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002192
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002193 SourceLocation BaseLoc
2194 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002195
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002196 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2197 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2198 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2199
2200 // C++ [class.base.init]p2:
2201 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002202 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002203 // of that class, the mem-initializer is ill-formed. A
2204 // mem-initializer-list can initialize a base class using any
2205 // name that denotes that base class type.
2206 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2207
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002208 if (EllipsisLoc.isValid()) {
2209 // This is a pack expansion.
2210 if (!BaseType->containsUnexpandedParameterPack()) {
2211 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002212 << SourceRange(BaseLoc, Args.getEndLoc());
2213
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002214 EllipsisLoc = SourceLocation();
2215 }
2216 } else {
2217 // Check for any unexpanded parameter packs.
2218 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2219 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002220
2221 if (Args.DiagnoseUnexpandedParameterPack(*this))
2222 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002223 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002224
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002225 // Check for direct and virtual base classes.
2226 const CXXBaseSpecifier *DirectBaseSpec = 0;
2227 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2228 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002229 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2230 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002231 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002232
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002233 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2234 VirtualBaseSpec);
2235
2236 // C++ [base.class.init]p2:
2237 // Unless the mem-initializer-id names a nonstatic data member of the
2238 // constructor's class or a direct or virtual base of that class, the
2239 // mem-initializer is ill-formed.
2240 if (!DirectBaseSpec && !VirtualBaseSpec) {
2241 // If the class has any dependent bases, then it's possible that
2242 // one of those types will resolve to the same type as
2243 // BaseType. Therefore, just treat this as a dependent base
2244 // class initialization. FIXME: Should we try to check the
2245 // initialization anyway? It seems odd.
2246 if (ClassDecl->hasAnyDependentBases())
2247 Dependent = true;
2248 else
2249 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2250 << BaseType << Context.getTypeDeclType(ClassDecl)
2251 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2252 }
2253 }
2254
2255 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002256 // Can't check initialization for a base of dependent type or when
2257 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002258 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002259
John McCallf85e1932011-06-15 23:02:42 +00002260 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Sebastian Redl6df65482011-09-24 17:48:25 +00002262 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2263 /*IsVirtual=*/false,
2264 Args.getStartLoc(), BaseInit,
2265 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002266 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002267
2268 // C++ [base.class.init]p2:
2269 // If a mem-initializer-id is ambiguous because it designates both
2270 // a direct non-virtual base class and an inherited virtual base
2271 // class, the mem-initializer is ill-formed.
2272 if (DirectBaseSpec && VirtualBaseSpec)
2273 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002274 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002275
2276 CXXBaseSpecifier *BaseSpec
2277 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2278 if (!BaseSpec)
2279 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2280
2281 // Initialize the base.
2282 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002283 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002284 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002285 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2286 Args.getEndLoc());
2287
2288 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002289 if (BaseInit.isInvalid())
2290 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002291
Sebastian Redl6df65482011-09-24 17:48:25 +00002292 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2293
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002294 // C++0x [class.base.init]p7:
2295 // The initialization of each base and member constitutes a
2296 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002297 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002298 if (BaseInit.isInvalid())
2299 return true;
2300
2301 // If we are in a dependent context, template instantiation will
2302 // perform this type-checking again. Just save the arguments that we
2303 // received in a ParenListExpr.
2304 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2305 // of the information that we have about the base
2306 // initializer. However, deconstructing the ASTs is a dicey process,
2307 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002308 if (CurContext->isDependentContext())
2309 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002310
Sean Huntcbb67482011-01-08 20:30:50 +00002311 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002312 BaseSpec->isVirtual(),
2313 Args.getStartLoc(),
2314 BaseInit.takeAs<Expr>(),
2315 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002316}
2317
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002318// Create a static_cast\<T&&>(expr).
2319static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2320 QualType ExprType = E->getType();
2321 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2322 SourceLocation ExprLoc = E->getLocStart();
2323 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2324 TargetType, ExprLoc);
2325
2326 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2327 SourceRange(ExprLoc, ExprLoc),
2328 E->getSourceRange()).take();
2329}
2330
Anders Carlssone5ef7402010-04-23 03:10:23 +00002331/// ImplicitInitializerKind - How an implicit base or member initializer should
2332/// initialize its base or member.
2333enum ImplicitInitializerKind {
2334 IIK_Default,
2335 IIK_Copy,
2336 IIK_Move
2337};
2338
Anders Carlssondefefd22010-04-23 02:00:02 +00002339static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002340BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002341 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002342 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002343 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002344 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002345 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002346 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2347 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002348
John McCall60d7b3a2010-08-24 06:29:42 +00002349 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002350
2351 switch (ImplicitInitKind) {
2352 case IIK_Default: {
2353 InitializationKind InitKind
2354 = InitializationKind::CreateDefault(Constructor->getLocation());
2355 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2356 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002357 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002358 break;
2359 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002360
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002361 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002362 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002363 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002364 ParmVarDecl *Param = Constructor->getParamDecl(0);
2365 QualType ParamType = Param->getType().getNonReferenceType();
2366
2367 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002368 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002369 Constructor->getLocation(), ParamType,
2370 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002371
Anders Carlssonc7957502010-04-24 22:02:54 +00002372 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002373 QualType ArgTy =
2374 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2375 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002376
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002377 if (Moving) {
2378 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2379 }
2380
John McCallf871d0c2010-08-07 06:22:56 +00002381 CXXCastPath BasePath;
2382 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002383 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2384 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002385 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002386 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002387
Anders Carlssone5ef7402010-04-23 03:10:23 +00002388 InitializationKind InitKind
2389 = InitializationKind::CreateDirect(Constructor->getLocation(),
2390 SourceLocation(), SourceLocation());
2391 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2392 &CopyCtorArg, 1);
2393 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002394 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002395 break;
2396 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002397 }
John McCall9ae2f072010-08-23 23:25:46 +00002398
Douglas Gregor53c374f2010-12-07 00:41:46 +00002399 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002400 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002401 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002402
Anders Carlssondefefd22010-04-23 02:00:02 +00002403 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002404 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002405 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2406 SourceLocation()),
2407 BaseSpec->isVirtual(),
2408 SourceLocation(),
2409 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002410 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002411 SourceLocation());
2412
Anders Carlssondefefd22010-04-23 02:00:02 +00002413 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002414}
2415
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002416static bool RefersToRValueRef(Expr *MemRef) {
2417 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2418 return Referenced->getType()->isRValueReferenceType();
2419}
2420
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002421static bool
2422BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002423 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002424 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002425 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002426 if (Field->isInvalidDecl())
2427 return true;
2428
Chandler Carruthf186b542010-06-29 23:50:44 +00002429 SourceLocation Loc = Constructor->getLocation();
2430
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002431 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2432 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002433 ParmVarDecl *Param = Constructor->getParamDecl(0);
2434 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002435
2436 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002437 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2438 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002439
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002440 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002441 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002442 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002443
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002444 if (Moving) {
2445 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2446 }
2447
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002448 // Build a reference to this field within the parameter.
2449 CXXScopeSpec SS;
2450 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2451 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002452 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2453 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002454 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002455 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002456 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002457 ParamType, Loc,
2458 /*IsArrow=*/false,
2459 SS,
2460 /*FirstQualifierInScope=*/0,
2461 MemberLookup,
2462 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002463 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002464 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002465
2466 // C++11 [class.copy]p15:
2467 // - if a member m has rvalue reference type T&&, it is direct-initialized
2468 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002469 if (RefersToRValueRef(CtorArg.get())) {
2470 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002471 }
2472
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002473 // When the field we are copying is an array, create index variables for
2474 // each dimension of the array. We use these index variables to subscript
2475 // the source array, and other clients (e.g., CodeGen) will perform the
2476 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002477 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002478 QualType BaseType = Field->getType();
2479 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002480 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002481 while (const ConstantArrayType *Array
2482 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002483 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002484 // Create the iteration variable for this array index.
2485 IdentifierInfo *IterationVarName = 0;
2486 {
2487 llvm::SmallString<8> Str;
2488 llvm::raw_svector_ostream OS(Str);
2489 OS << "__i" << IndexVariables.size();
2490 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2491 }
2492 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002493 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002494 IterationVarName, SizeType,
2495 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002496 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002497 IndexVariables.push_back(IterationVar);
2498
2499 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002500 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002501 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002502 assert(!IterationVarRef.isInvalid() &&
2503 "Reference to invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002504
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002505 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002506 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002507 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002508 Loc);
2509 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002510 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002511
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002512 BaseType = Array->getElementType();
2513 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002514
2515 // The array subscript expression is an lvalue, which is wrong for moving.
2516 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002517 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002518
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002519 // Construct the entity that we will be initializing. For an array, this
2520 // will be first element in the array, which may require several levels
2521 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002522 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002523 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002524 if (Indirect)
2525 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2526 else
2527 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002528 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2529 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2530 0,
2531 Entities.back()));
2532
2533 // Direct-initialize to use the copy constructor.
2534 InitializationKind InitKind =
2535 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2536
Sebastian Redl74e611a2011-09-04 18:14:28 +00002537 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002538 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002539 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002540
John McCall60d7b3a2010-08-24 06:29:42 +00002541 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002542 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002543 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002544 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002545 if (MemberInit.isInvalid())
2546 return true;
2547
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002548 if (Indirect) {
2549 assert(IndexVariables.size() == 0 &&
2550 "Indirect field improperly initialized");
2551 CXXMemberInit
2552 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2553 Loc, Loc,
2554 MemberInit.takeAs<Expr>(),
2555 Loc);
2556 } else
2557 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2558 Loc, MemberInit.takeAs<Expr>(),
2559 Loc,
2560 IndexVariables.data(),
2561 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002562 return false;
2563 }
2564
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002565 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2566
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002567 QualType FieldBaseElementType =
2568 SemaRef.Context.getBaseElementType(Field->getType());
2569
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002570 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002571 InitializedEntity InitEntity
2572 = Indirect? InitializedEntity::InitializeMember(Indirect)
2573 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002574 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002575 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002576
2577 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002578 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002579 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002580
Douglas Gregor53c374f2010-12-07 00:41:46 +00002581 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002582 if (MemberInit.isInvalid())
2583 return true;
2584
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002585 if (Indirect)
2586 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2587 Indirect, Loc,
2588 Loc,
2589 MemberInit.get(),
2590 Loc);
2591 else
2592 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2593 Field, Loc, Loc,
2594 MemberInit.get(),
2595 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002596 return false;
2597 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002598
Sean Hunt1f2f3842011-05-17 00:19:05 +00002599 if (!Field->getParent()->isUnion()) {
2600 if (FieldBaseElementType->isReferenceType()) {
2601 SemaRef.Diag(Constructor->getLocation(),
2602 diag::err_uninitialized_member_in_ctor)
2603 << (int)Constructor->isImplicit()
2604 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2605 << 0 << Field->getDeclName();
2606 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2607 return true;
2608 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002609
Sean Hunt1f2f3842011-05-17 00:19:05 +00002610 if (FieldBaseElementType.isConstQualified()) {
2611 SemaRef.Diag(Constructor->getLocation(),
2612 diag::err_uninitialized_member_in_ctor)
2613 << (int)Constructor->isImplicit()
2614 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2615 << 1 << Field->getDeclName();
2616 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2617 return true;
2618 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002619 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002620
John McCallf85e1932011-06-15 23:02:42 +00002621 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2622 FieldBaseElementType->isObjCRetainableType() &&
2623 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2624 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2625 // Instant objects:
2626 // Default-initialize Objective-C pointers to NULL.
2627 CXXMemberInit
2628 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2629 Loc, Loc,
2630 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2631 Loc);
2632 return false;
2633 }
2634
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002635 // Nothing to initialize.
2636 CXXMemberInit = 0;
2637 return false;
2638}
John McCallf1860e52010-05-20 23:23:51 +00002639
2640namespace {
2641struct BaseAndFieldInfo {
2642 Sema &S;
2643 CXXConstructorDecl *Ctor;
2644 bool AnyErrorsInInits;
2645 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002646 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002647 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002648
2649 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2650 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002651 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2652 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002653 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002654 else if (Generated && Ctor->isMoveConstructor())
2655 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002656 else
2657 IIK = IIK_Default;
2658 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002659
2660 bool isImplicitCopyOrMove() const {
2661 switch (IIK) {
2662 case IIK_Copy:
2663 case IIK_Move:
2664 return true;
2665
2666 case IIK_Default:
2667 return false;
2668 }
2669
2670 return false;
2671 }
John McCallf1860e52010-05-20 23:23:51 +00002672};
2673}
2674
Richard Smitha4950662011-09-19 13:34:43 +00002675/// \brief Determine whether the given indirect field declaration is somewhere
2676/// within an anonymous union.
2677static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2678 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2679 CEnd = F->chain_end();
2680 C != CEnd; ++C)
2681 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2682 if (Record->isUnion())
2683 return true;
2684
2685 return false;
2686}
2687
Douglas Gregorddb21472011-11-02 23:04:16 +00002688/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2689/// array type.
2690static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2691 if (T->isIncompleteArrayType())
2692 return true;
2693
2694 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2695 if (!ArrayT->getSize())
2696 return true;
2697
2698 T = ArrayT->getElementType();
2699 }
2700
2701 return false;
2702}
2703
Richard Smith7a614d82011-06-11 17:19:42 +00002704static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002705 FieldDecl *Field,
2706 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002707
Chandler Carruthe861c602010-06-30 02:59:29 +00002708 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002709 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002710 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002711 return false;
2712 }
2713
Richard Smith7a614d82011-06-11 17:19:42 +00002714 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2715 // has a brace-or-equal-initializer, the entity is initialized as specified
2716 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002717 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002718 CXXCtorInitializer *Init;
2719 if (Indirect)
2720 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2721 SourceLocation(),
2722 SourceLocation(), 0,
2723 SourceLocation());
2724 else
2725 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2726 SourceLocation(),
2727 SourceLocation(), 0,
2728 SourceLocation());
2729 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002730 return false;
2731 }
2732
Richard Smithc115f632011-09-18 11:14:50 +00002733 // Don't build an implicit initializer for union members if none was
2734 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002735 if (Field->getParent()->isUnion() ||
2736 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002737 return false;
2738
Douglas Gregorddb21472011-11-02 23:04:16 +00002739 // Don't initialize incomplete or zero-length arrays.
2740 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2741 return false;
2742
John McCallf1860e52010-05-20 23:23:51 +00002743 // Don't try to build an implicit initializer if there were semantic
2744 // errors in any of the initializers (and therefore we might be
2745 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002746 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002747 return false;
2748
Sean Huntcbb67482011-01-08 20:30:50 +00002749 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002750 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2751 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002752 return true;
John McCallf1860e52010-05-20 23:23:51 +00002753
Francois Pichet00eb3f92010-12-04 09:14:42 +00002754 if (Init)
2755 Info.AllToInit.push_back(Init);
2756
John McCallf1860e52010-05-20 23:23:51 +00002757 return false;
2758}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002759
2760bool
2761Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2762 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002763 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002764 Constructor->setNumCtorInitializers(1);
2765 CXXCtorInitializer **initializer =
2766 new (Context) CXXCtorInitializer*[1];
2767 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2768 Constructor->setCtorInitializers(initializer);
2769
Sean Huntb76af9c2011-05-03 23:05:34 +00002770 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2771 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2772 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2773 }
2774
Sean Huntc1598702011-05-05 00:05:47 +00002775 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002776
Sean Hunt059ce0d2011-05-01 07:04:31 +00002777 return false;
2778}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002779
John McCallb77115d2011-06-17 00:18:42 +00002780bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2781 CXXCtorInitializer **Initializers,
2782 unsigned NumInitializers,
2783 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002784 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002785 // Just store the initializers as written, they will be checked during
2786 // instantiation.
2787 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002788 Constructor->setNumCtorInitializers(NumInitializers);
2789 CXXCtorInitializer **baseOrMemberInitializers =
2790 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002791 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002792 NumInitializers * sizeof(CXXCtorInitializer*));
2793 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002794 }
2795
2796 return false;
2797 }
2798
John McCallf1860e52010-05-20 23:23:51 +00002799 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002800
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002801 // We need to build the initializer AST according to order of construction
2802 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002803 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002804 if (!ClassDecl)
2805 return true;
2806
Eli Friedman80c30da2009-11-09 19:20:36 +00002807 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002808
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002809 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002810 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002811
2812 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002813 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002814 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002815 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002816 }
2817
Anders Carlsson711f34a2010-04-21 19:52:01 +00002818 // Keep track of the direct virtual bases.
2819 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2820 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2821 E = ClassDecl->bases_end(); I != E; ++I) {
2822 if (I->isVirtual())
2823 DirectVBases.insert(I);
2824 }
2825
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002826 // Push virtual bases before others.
2827 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2828 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2829
Sean Huntcbb67482011-01-08 20:30:50 +00002830 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002831 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2832 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002833 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002834 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002835 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002836 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002837 VBase, IsInheritedVirtualBase,
2838 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002839 HadError = true;
2840 continue;
2841 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002842
John McCallf1860e52010-05-20 23:23:51 +00002843 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002844 }
2845 }
Mike Stump1eb44332009-09-09 15:08:12 +00002846
John McCallf1860e52010-05-20 23:23:51 +00002847 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002848 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2849 E = ClassDecl->bases_end(); Base != E; ++Base) {
2850 // Virtuals are in the virtual base list and already constructed.
2851 if (Base->isVirtual())
2852 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Sean Huntcbb67482011-01-08 20:30:50 +00002854 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002855 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2856 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002857 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002858 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002859 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002860 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002861 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002862 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002863 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002864 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002865
John McCallf1860e52010-05-20 23:23:51 +00002866 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002867 }
2868 }
Mike Stump1eb44332009-09-09 15:08:12 +00002869
John McCallf1860e52010-05-20 23:23:51 +00002870 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002871 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2872 MemEnd = ClassDecl->decls_end();
2873 Mem != MemEnd; ++Mem) {
2874 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002875 // C++ [class.bit]p2:
2876 // A declaration for a bit-field that omits the identifier declares an
2877 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2878 // initialized.
2879 if (F->isUnnamedBitfield())
2880 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002881
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002882 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002883 // handle anonymous struct/union fields based on their individual
2884 // indirect fields.
2885 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2886 continue;
2887
2888 if (CollectFieldInitializer(*this, Info, F))
2889 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002890 continue;
2891 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002892
2893 // Beyond this point, we only consider default initialization.
2894 if (Info.IIK != IIK_Default)
2895 continue;
2896
2897 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2898 if (F->getType()->isIncompleteArrayType()) {
2899 assert(ClassDecl->hasFlexibleArrayMember() &&
2900 "Incomplete array type is not valid");
2901 continue;
2902 }
2903
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002904 // Initialize each field of an anonymous struct individually.
2905 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2906 HadError = true;
2907
2908 continue;
2909 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002910 }
Mike Stump1eb44332009-09-09 15:08:12 +00002911
John McCallf1860e52010-05-20 23:23:51 +00002912 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002913 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002914 Constructor->setNumCtorInitializers(NumInitializers);
2915 CXXCtorInitializer **baseOrMemberInitializers =
2916 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002917 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002918 NumInitializers * sizeof(CXXCtorInitializer*));
2919 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002920
John McCallef027fe2010-03-16 21:39:52 +00002921 // Constructors implicitly reference the base and member
2922 // destructors.
2923 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2924 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002925 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002926
2927 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002928}
2929
Eli Friedman6347f422009-07-21 19:28:10 +00002930static void *GetKeyForTopLevelField(FieldDecl *Field) {
2931 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002932 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002933 if (RT->getDecl()->isAnonymousStructOrUnion())
2934 return static_cast<void *>(RT->getDecl());
2935 }
2936 return static_cast<void *>(Field);
2937}
2938
Anders Carlssonea356fb2010-04-02 05:42:15 +00002939static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002940 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002941}
2942
Anders Carlssonea356fb2010-04-02 05:42:15 +00002943static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002944 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002945 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002946 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002947
Eli Friedman6347f422009-07-21 19:28:10 +00002948 // For fields injected into the class via declaration of an anonymous union,
2949 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002950 FieldDecl *Field = Member->getAnyMember();
2951
John McCall3c3ccdb2010-04-10 09:28:51 +00002952 // If the field is a member of an anonymous struct or union, our key
2953 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002954 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002955 if (RD->isAnonymousStructOrUnion()) {
2956 while (true) {
2957 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2958 if (Parent->isAnonymousStructOrUnion())
2959 RD = Parent;
2960 else
2961 break;
2962 }
2963
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002964 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002965 }
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002967 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002968}
2969
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002970static void
2971DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002972 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002973 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002974 unsigned NumInits) {
2975 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002976 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002978 // Don't check initializers order unless the warning is enabled at the
2979 // location of at least one initializer.
2980 bool ShouldCheckOrder = false;
2981 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002982 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002983 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2984 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00002985 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002986 ShouldCheckOrder = true;
2987 break;
2988 }
2989 }
2990 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002991 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002992
John McCalld6ca8da2010-04-10 07:37:23 +00002993 // Build the list of bases and members in the order that they'll
2994 // actually be initialized. The explicit initializers should be in
2995 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002996 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Anders Carlsson071d6102010-04-02 03:38:04 +00002998 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2999
John McCalld6ca8da2010-04-10 07:37:23 +00003000 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003001 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003002 ClassDecl->vbases_begin(),
3003 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003004 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003005
John McCalld6ca8da2010-04-10 07:37:23 +00003006 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003007 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003008 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003009 if (Base->isVirtual())
3010 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003011 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
John McCalld6ca8da2010-04-10 07:37:23 +00003014 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003015 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003016 E = ClassDecl->field_end(); Field != E; ++Field) {
3017 if (Field->isUnnamedBitfield())
3018 continue;
3019
John McCalld6ca8da2010-04-10 07:37:23 +00003020 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003021 }
3022
John McCalld6ca8da2010-04-10 07:37:23 +00003023 unsigned NumIdealInits = IdealInitKeys.size();
3024 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003025
Sean Huntcbb67482011-01-08 20:30:50 +00003026 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003027 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003028 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003029 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003030
3031 // Scan forward to try to find this initializer in the idealized
3032 // initializers list.
3033 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3034 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003035 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003036
3037 // If we didn't find this initializer, it must be because we
3038 // scanned past it on a previous iteration. That can only
3039 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003040 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003041 Sema::SemaDiagnosticBuilder D =
3042 SemaRef.Diag(PrevInit->getSourceLocation(),
3043 diag::warn_initializer_out_of_order);
3044
Francois Pichet00eb3f92010-12-04 09:14:42 +00003045 if (PrevInit->isAnyMemberInitializer())
3046 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003047 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003048 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003049
Francois Pichet00eb3f92010-12-04 09:14:42 +00003050 if (Init->isAnyMemberInitializer())
3051 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003052 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003053 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003054
3055 // Move back to the initializer's location in the ideal list.
3056 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3057 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003058 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003059
3060 assert(IdealIndex != NumIdealInits &&
3061 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003062 }
John McCalld6ca8da2010-04-10 07:37:23 +00003063
3064 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003065 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003066}
3067
John McCall3c3ccdb2010-04-10 09:28:51 +00003068namespace {
3069bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003070 CXXCtorInitializer *Init,
3071 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003072 if (!PrevInit) {
3073 PrevInit = Init;
3074 return false;
3075 }
3076
3077 if (FieldDecl *Field = Init->getMember())
3078 S.Diag(Init->getSourceLocation(),
3079 diag::err_multiple_mem_initialization)
3080 << Field->getDeclName()
3081 << Init->getSourceRange();
3082 else {
John McCallf4c73712011-01-19 06:33:43 +00003083 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003084 assert(BaseClass && "neither field nor base");
3085 S.Diag(Init->getSourceLocation(),
3086 diag::err_multiple_base_initialization)
3087 << QualType(BaseClass, 0)
3088 << Init->getSourceRange();
3089 }
3090 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3091 << 0 << PrevInit->getSourceRange();
3092
3093 return true;
3094}
3095
Sean Huntcbb67482011-01-08 20:30:50 +00003096typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003097typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3098
3099bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003100 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003101 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003102 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003103 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003104 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003105
3106 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003107 if (Parent->isUnion()) {
3108 UnionEntry &En = Unions[Parent];
3109 if (En.first && En.first != Child) {
3110 S.Diag(Init->getSourceLocation(),
3111 diag::err_multiple_mem_union_initialization)
3112 << Field->getDeclName()
3113 << Init->getSourceRange();
3114 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3115 << 0 << En.second->getSourceRange();
3116 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003117 }
3118 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003119 En.first = Child;
3120 En.second = Init;
3121 }
David Blaikie6fe29652011-11-17 06:01:57 +00003122 if (!Parent->isAnonymousStructOrUnion())
3123 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003124 }
3125
3126 Child = Parent;
3127 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003128 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003129
3130 return false;
3131}
3132}
3133
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003134/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003135void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003136 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003137 CXXCtorInitializer **meminits,
3138 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003139 bool AnyErrors) {
3140 if (!ConstructorDecl)
3141 return;
3142
3143 AdjustDeclIfTemplate(ConstructorDecl);
3144
3145 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003146 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003147
3148 if (!Constructor) {
3149 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3150 return;
3151 }
3152
Sean Huntcbb67482011-01-08 20:30:50 +00003153 CXXCtorInitializer **MemInits =
3154 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003155
3156 // Mapping for the duplicate initializers check.
3157 // For member initializers, this is keyed with a FieldDecl*.
3158 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003159 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003160
3161 // Mapping for the inconsistent anonymous-union initializers check.
3162 RedundantUnionMap MemberUnions;
3163
Anders Carlssonea356fb2010-04-02 05:42:15 +00003164 bool HadError = false;
3165 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003166 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003167
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003168 // Set the source order index.
3169 Init->setSourceOrder(i);
3170
Francois Pichet00eb3f92010-12-04 09:14:42 +00003171 if (Init->isAnyMemberInitializer()) {
3172 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003173 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3174 CheckRedundantUnionInit(*this, Init, MemberUnions))
3175 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003176 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003177 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3178 if (CheckRedundantInit(*this, Init, Members[Key]))
3179 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003180 } else {
3181 assert(Init->isDelegatingInitializer());
3182 // This must be the only initializer
3183 if (i != 0 || NumMemInits > 1) {
3184 Diag(MemInits[0]->getSourceLocation(),
3185 diag::err_delegating_initializer_alone)
3186 << MemInits[0]->getSourceRange();
3187 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003188 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003189 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003190 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003191 // Return immediately as the initializer is set.
3192 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003193 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003194 }
3195
Anders Carlssonea356fb2010-04-02 05:42:15 +00003196 if (HadError)
3197 return;
3198
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003199 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003200
Sean Huntcbb67482011-01-08 20:30:50 +00003201 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003202}
3203
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003204void
John McCallef027fe2010-03-16 21:39:52 +00003205Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3206 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003207 // Ignore dependent contexts. Also ignore unions, since their members never
3208 // have destructors implicitly called.
3209 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003210 return;
John McCall58e6f342010-03-16 05:22:47 +00003211
3212 // FIXME: all the access-control diagnostics are positioned on the
3213 // field/base declaration. That's probably good; that said, the
3214 // user might reasonably want to know why the destructor is being
3215 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003216
Anders Carlsson9f853df2009-11-17 04:44:12 +00003217 // Non-static data members.
3218 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3219 E = ClassDecl->field_end(); I != E; ++I) {
3220 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003221 if (Field->isInvalidDecl())
3222 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003223
3224 // Don't destroy incomplete or zero-length arrays.
3225 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3226 continue;
3227
Anders Carlsson9f853df2009-11-17 04:44:12 +00003228 QualType FieldType = Context.getBaseElementType(Field->getType());
3229
3230 const RecordType* RT = FieldType->getAs<RecordType>();
3231 if (!RT)
3232 continue;
3233
3234 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003235 if (FieldClassDecl->isInvalidDecl())
3236 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003237 if (FieldClassDecl->hasTrivialDestructor())
3238 continue;
3239
Douglas Gregordb89f282010-07-01 22:47:18 +00003240 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003241 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003242 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003243 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003244 << Field->getDeclName()
3245 << FieldType);
3246
John McCallef027fe2010-03-16 21:39:52 +00003247 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003248 }
3249
John McCall58e6f342010-03-16 05:22:47 +00003250 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3251
Anders Carlsson9f853df2009-11-17 04:44:12 +00003252 // Bases.
3253 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3254 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003255 // Bases are always records in a well-formed non-dependent class.
3256 const RecordType *RT = Base->getType()->getAs<RecordType>();
3257
3258 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003259 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003260 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003261
John McCall58e6f342010-03-16 05:22:47 +00003262 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003263 // If our base class is invalid, we probably can't get its dtor anyway.
3264 if (BaseClassDecl->isInvalidDecl())
3265 continue;
3266 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003267 if (BaseClassDecl->hasTrivialDestructor())
3268 continue;
John McCall58e6f342010-03-16 05:22:47 +00003269
Douglas Gregordb89f282010-07-01 22:47:18 +00003270 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003271 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003272
3273 // FIXME: caret should be on the start of the class name
3274 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003275 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003276 << Base->getType()
3277 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003278
John McCallef027fe2010-03-16 21:39:52 +00003279 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003280 }
3281
3282 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003283 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3284 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003285
3286 // Bases are always records in a well-formed non-dependent class.
3287 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3288
3289 // Ignore direct virtual bases.
3290 if (DirectVirtualBases.count(RT))
3291 continue;
3292
John McCall58e6f342010-03-16 05:22:47 +00003293 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003294 // If our base class is invalid, we probably can't get its dtor anyway.
3295 if (BaseClassDecl->isInvalidDecl())
3296 continue;
3297 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003298 if (BaseClassDecl->hasTrivialDestructor())
3299 continue;
John McCall58e6f342010-03-16 05:22:47 +00003300
Douglas Gregordb89f282010-07-01 22:47:18 +00003301 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003302 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003303 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003304 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003305 << VBase->getType());
3306
John McCallef027fe2010-03-16 21:39:52 +00003307 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003308 }
3309}
3310
John McCalld226f652010-08-21 09:40:31 +00003311void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003312 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003313 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Mike Stump1eb44332009-09-09 15:08:12 +00003315 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003316 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003317 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003318}
3319
Mike Stump1eb44332009-09-09 15:08:12 +00003320bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003321 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003322 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003323 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003324 else
John McCall94c3b562010-08-18 09:41:07 +00003325 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003326}
3327
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003328bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003329 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003330 if (!getLangOptions().CPlusPlus)
3331 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Anders Carlsson11f21a02009-03-23 19:10:31 +00003333 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003334 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Ted Kremenek6217b802009-07-29 21:53:49 +00003336 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003337 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003338 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003339 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003340
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003341 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003342 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003343 }
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Ted Kremenek6217b802009-07-29 21:53:49 +00003345 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003346 if (!RT)
3347 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003348
John McCall86ff3082010-02-04 22:26:26 +00003349 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003350
John McCall94c3b562010-08-18 09:41:07 +00003351 // We can't answer whether something is abstract until it has a
3352 // definition. If it's currently being defined, we'll walk back
3353 // over all the declarations when we have a full definition.
3354 const CXXRecordDecl *Def = RD->getDefinition();
3355 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003356 return false;
3357
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003358 if (!RD->isAbstract())
3359 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003361 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003362 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003363
John McCall94c3b562010-08-18 09:41:07 +00003364 return true;
3365}
3366
3367void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3368 // Check if we've already emitted the list of pure virtual functions
3369 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003370 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003371 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003373 CXXFinalOverriderMap FinalOverriders;
3374 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003376 // Keep a set of seen pure methods so we won't diagnose the same method
3377 // more than once.
3378 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3379
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003380 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3381 MEnd = FinalOverriders.end();
3382 M != MEnd;
3383 ++M) {
3384 for (OverridingMethods::iterator SO = M->second.begin(),
3385 SOEnd = M->second.end();
3386 SO != SOEnd; ++SO) {
3387 // C++ [class.abstract]p4:
3388 // A class is abstract if it contains or inherits at least one
3389 // pure virtual function for which the final overrider is pure
3390 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003392 //
3393 if (SO->second.size() != 1)
3394 continue;
3395
3396 if (!SO->second.front().Method->isPure())
3397 continue;
3398
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003399 if (!SeenPureMethods.insert(SO->second.front().Method))
3400 continue;
3401
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003402 Diag(SO->second.front().Method->getLocation(),
3403 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003404 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003405 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003406 }
3407
3408 if (!PureVirtualClassDiagSet)
3409 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3410 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003411}
3412
Anders Carlsson8211eff2009-03-24 01:19:16 +00003413namespace {
John McCall94c3b562010-08-18 09:41:07 +00003414struct AbstractUsageInfo {
3415 Sema &S;
3416 CXXRecordDecl *Record;
3417 CanQualType AbstractType;
3418 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003419
John McCall94c3b562010-08-18 09:41:07 +00003420 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3421 : S(S), Record(Record),
3422 AbstractType(S.Context.getCanonicalType(
3423 S.Context.getTypeDeclType(Record))),
3424 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003425
John McCall94c3b562010-08-18 09:41:07 +00003426 void DiagnoseAbstractType() {
3427 if (Invalid) return;
3428 S.DiagnoseAbstractType(Record);
3429 Invalid = true;
3430 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003431
John McCall94c3b562010-08-18 09:41:07 +00003432 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3433};
3434
3435struct CheckAbstractUsage {
3436 AbstractUsageInfo &Info;
3437 const NamedDecl *Ctx;
3438
3439 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3440 : Info(Info), Ctx(Ctx) {}
3441
3442 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3443 switch (TL.getTypeLocClass()) {
3444#define ABSTRACT_TYPELOC(CLASS, PARENT)
3445#define TYPELOC(CLASS, PARENT) \
3446 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3447#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003448 }
John McCall94c3b562010-08-18 09:41:07 +00003449 }
Mike Stump1eb44332009-09-09 15:08:12 +00003450
John McCall94c3b562010-08-18 09:41:07 +00003451 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3452 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3453 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003454 if (!TL.getArg(I))
3455 continue;
3456
John McCall94c3b562010-08-18 09:41:07 +00003457 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3458 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003459 }
John McCall94c3b562010-08-18 09:41:07 +00003460 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003461
John McCall94c3b562010-08-18 09:41:07 +00003462 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3463 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3464 }
Mike Stump1eb44332009-09-09 15:08:12 +00003465
John McCall94c3b562010-08-18 09:41:07 +00003466 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3467 // Visit the type parameters from a permissive context.
3468 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3469 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3470 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3471 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3472 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3473 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003474 }
John McCall94c3b562010-08-18 09:41:07 +00003475 }
Mike Stump1eb44332009-09-09 15:08:12 +00003476
John McCall94c3b562010-08-18 09:41:07 +00003477 // Visit pointee types from a permissive context.
3478#define CheckPolymorphic(Type) \
3479 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3480 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3481 }
3482 CheckPolymorphic(PointerTypeLoc)
3483 CheckPolymorphic(ReferenceTypeLoc)
3484 CheckPolymorphic(MemberPointerTypeLoc)
3485 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003486 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003487
John McCall94c3b562010-08-18 09:41:07 +00003488 /// Handle all the types we haven't given a more specific
3489 /// implementation for above.
3490 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3491 // Every other kind of type that we haven't called out already
3492 // that has an inner type is either (1) sugar or (2) contains that
3493 // inner type in some way as a subobject.
3494 if (TypeLoc Next = TL.getNextTypeLoc())
3495 return Visit(Next, Sel);
3496
3497 // If there's no inner type and we're in a permissive context,
3498 // don't diagnose.
3499 if (Sel == Sema::AbstractNone) return;
3500
3501 // Check whether the type matches the abstract type.
3502 QualType T = TL.getType();
3503 if (T->isArrayType()) {
3504 Sel = Sema::AbstractArrayType;
3505 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003506 }
John McCall94c3b562010-08-18 09:41:07 +00003507 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3508 if (CT != Info.AbstractType) return;
3509
3510 // It matched; do some magic.
3511 if (Sel == Sema::AbstractArrayType) {
3512 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3513 << T << TL.getSourceRange();
3514 } else {
3515 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3516 << Sel << T << TL.getSourceRange();
3517 }
3518 Info.DiagnoseAbstractType();
3519 }
3520};
3521
3522void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3523 Sema::AbstractDiagSelID Sel) {
3524 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3525}
3526
3527}
3528
3529/// Check for invalid uses of an abstract type in a method declaration.
3530static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3531 CXXMethodDecl *MD) {
3532 // No need to do the check on definitions, which require that
3533 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003534 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003535 return;
3536
3537 // For safety's sake, just ignore it if we don't have type source
3538 // information. This should never happen for non-implicit methods,
3539 // but...
3540 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3541 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3542}
3543
3544/// Check for invalid uses of an abstract type within a class definition.
3545static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3546 CXXRecordDecl *RD) {
3547 for (CXXRecordDecl::decl_iterator
3548 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3549 Decl *D = *I;
3550 if (D->isImplicit()) continue;
3551
3552 // Methods and method templates.
3553 if (isa<CXXMethodDecl>(D)) {
3554 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3555 } else if (isa<FunctionTemplateDecl>(D)) {
3556 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3557 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3558
3559 // Fields and static variables.
3560 } else if (isa<FieldDecl>(D)) {
3561 FieldDecl *FD = cast<FieldDecl>(D);
3562 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3563 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3564 } else if (isa<VarDecl>(D)) {
3565 VarDecl *VD = cast<VarDecl>(D);
3566 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3567 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3568
3569 // Nested classes and class templates.
3570 } else if (isa<CXXRecordDecl>(D)) {
3571 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3572 } else if (isa<ClassTemplateDecl>(D)) {
3573 CheckAbstractClassUsage(Info,
3574 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3575 }
3576 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003577}
3578
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003579/// \brief Perform semantic checks on a class definition that has been
3580/// completing, introducing implicitly-declared members, checking for
3581/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003582void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003583 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003584 return;
3585
John McCall94c3b562010-08-18 09:41:07 +00003586 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3587 AbstractUsageInfo Info(*this, Record);
3588 CheckAbstractClassUsage(Info, Record);
3589 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003590
3591 // If this is not an aggregate type and has no user-declared constructor,
3592 // complain about any non-static data members of reference or const scalar
3593 // type, since they will never get initializers.
3594 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3595 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3596 bool Complained = false;
3597 for (RecordDecl::field_iterator F = Record->field_begin(),
3598 FEnd = Record->field_end();
3599 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003600 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003601 continue;
3602
Douglas Gregor325e5932010-04-15 00:00:53 +00003603 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003604 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003605 if (!Complained) {
3606 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3607 << Record->getTagKind() << Record;
3608 Complained = true;
3609 }
3610
3611 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3612 << F->getType()->isReferenceType()
3613 << F->getDeclName();
3614 }
3615 }
3616 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003617
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003618 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003619 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003620
3621 if (Record->getIdentifier()) {
3622 // C++ [class.mem]p13:
3623 // If T is the name of a class, then each of the following shall have a
3624 // name different from T:
3625 // - every member of every anonymous union that is a member of class T.
3626 //
3627 // C++ [class.mem]p14:
3628 // In addition, if class T has a user-declared constructor (12.1), every
3629 // non-static data member of class T shall have a name different from T.
3630 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003631 R.first != R.second; ++R.first) {
3632 NamedDecl *D = *R.first;
3633 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3634 isa<IndirectFieldDecl>(D)) {
3635 Diag(D->getLocation(), diag::err_member_name_of_class)
3636 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003637 break;
3638 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003639 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003640 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003641
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003642 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003643 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003644 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003645 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003646 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3647 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3648 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003649
3650 // See if a method overloads virtual methods in a base
3651 /// class without overriding any.
3652 if (!Record->isDependentType()) {
3653 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3654 MEnd = Record->method_end();
3655 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003656 if (!(*M)->isStatic())
3657 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003658 }
3659 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003660
Richard Smith9f569cc2011-10-01 02:31:28 +00003661 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3662 // function that is not a constructor declares that member function to be
3663 // const. [...] The class of which that function is a member shall be
3664 // a literal type.
3665 //
3666 // It's fine to diagnose constructors here too: such constructors cannot
3667 // produce a constant expression, so are ill-formed (no diagnostic required).
3668 //
3669 // If the class has virtual bases, any constexpr members will already have
3670 // been diagnosed by the checks performed on the member declaration, so
3671 // suppress this (less useful) diagnostic.
3672 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3673 !Record->isLiteral() && !Record->getNumVBases()) {
3674 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3675 MEnd = Record->method_end();
3676 M != MEnd; ++M) {
3677 if ((*M)->isConstexpr()) {
3678 switch (Record->getTemplateSpecializationKind()) {
3679 case TSK_ImplicitInstantiation:
3680 case TSK_ExplicitInstantiationDeclaration:
3681 case TSK_ExplicitInstantiationDefinition:
3682 // If a template instantiates to a non-literal type, but its members
3683 // instantiate to constexpr functions, the template is technically
3684 // ill-formed, but we allow it for sanity. Such members are treated as
3685 // non-constexpr.
3686 (*M)->setConstexpr(false);
3687 continue;
3688
3689 case TSK_Undeclared:
3690 case TSK_ExplicitSpecialization:
3691 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3692 PDiag(diag::err_constexpr_method_non_literal));
3693 break;
3694 }
3695
3696 // Only produce one error per class.
3697 break;
3698 }
3699 }
3700 }
3701
Sebastian Redlf677ea32011-02-05 19:23:19 +00003702 // Declare inherited constructors. We do this eagerly here because:
3703 // - The standard requires an eager diagnostic for conflicting inherited
3704 // constructors from different classes.
3705 // - The lazy declaration of the other implicit constructors is so as to not
3706 // waste space and performance on classes that are not meant to be
3707 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3708 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003709 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003710
Sean Hunteb88ae52011-05-23 21:07:59 +00003711 if (!Record->isDependentType())
3712 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003713}
3714
3715void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003716 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3717 ME = Record->method_end();
3718 MI != ME; ++MI) {
3719 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3720 switch (getSpecialMember(*MI)) {
3721 case CXXDefaultConstructor:
3722 CheckExplicitlyDefaultedDefaultConstructor(
3723 cast<CXXConstructorDecl>(*MI));
3724 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003725
Sean Huntcb45a0f2011-05-12 22:46:25 +00003726 case CXXDestructor:
3727 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3728 break;
3729
3730 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003731 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3732 break;
3733
Sean Huntcb45a0f2011-05-12 22:46:25 +00003734 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003735 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003736 break;
3737
Sean Hunt82713172011-05-25 23:16:36 +00003738 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003739 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003740 break;
3741
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003742 case CXXMoveAssignment:
3743 CheckExplicitlyDefaultedMoveAssignment(*MI);
3744 break;
3745
3746 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003747 llvm_unreachable("non-special member explicitly defaulted!");
3748 }
Sean Hunt001cad92011-05-10 00:49:42 +00003749 }
3750 }
3751
Sean Hunt001cad92011-05-10 00:49:42 +00003752}
3753
3754void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3755 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3756
3757 // Whether this was the first-declared instance of the constructor.
3758 // This affects whether we implicitly add an exception spec (and, eventually,
3759 // constexpr). It is also ill-formed to explicitly default a constructor such
3760 // that it would be deleted. (C++0x [decl.fct.def.default])
3761 bool First = CD == CD->getCanonicalDecl();
3762
Sean Hunt49634cf2011-05-13 06:10:58 +00003763 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003764 if (CD->getNumParams() != 0) {
3765 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3766 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003767 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003768 }
3769
3770 ImplicitExceptionSpecification Spec
3771 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3772 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003773 if (EPI.ExceptionSpecType == EST_Delayed) {
3774 // Exception specification depends on some deferred part of the class. We'll
3775 // try again when the class's definition has been fully processed.
3776 return;
3777 }
Sean Hunt001cad92011-05-10 00:49:42 +00003778 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3779 *ExceptionType = Context.getFunctionType(
3780 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3781
Richard Smith61802452011-12-22 02:22:31 +00003782 // C++11 [dcl.fct.def.default]p2:
3783 // An explicitly-defaulted function may be declared constexpr only if it
3784 // would have been implicitly declared as constexpr,
3785 if (CD->isConstexpr()) {
3786 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3787 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3788 << CXXDefaultConstructor;
3789 HadError = true;
3790 }
3791 }
3792 // and may have an explicit exception-specification only if it is compatible
3793 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003794 if (CtorType->hasExceptionSpec()) {
3795 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003796 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003797 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003798 PDiag(),
3799 ExceptionType, SourceLocation(),
3800 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003801 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003802 }
Richard Smith61802452011-12-22 02:22:31 +00003803 }
3804
3805 // If a function is explicitly defaulted on its first declaration,
3806 if (First) {
3807 // -- it is implicitly considered to be constexpr if the implicit
3808 // definition would be,
3809 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3810
3811 // -- it is implicitly considered to have the same
3812 // exception-specification as if it had been implicitly declared
3813 //
3814 // FIXME: a compatible, but different, explicit exception specification
3815 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003816 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003817 }
Sean Huntca46d132011-05-12 03:51:48 +00003818
Sean Hunt49634cf2011-05-13 06:10:58 +00003819 if (HadError) {
3820 CD->setInvalidDecl();
3821 return;
3822 }
3823
Sean Hunte16da072011-10-10 06:18:57 +00003824 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003825 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003826 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003827 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003828 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003829 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003830 CD->setInvalidDecl();
3831 }
3832 }
3833}
3834
3835void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3836 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3837
3838 // Whether this was the first-declared instance of the constructor.
3839 bool First = CD == CD->getCanonicalDecl();
3840
3841 bool HadError = false;
3842 if (CD->getNumParams() != 1) {
3843 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3844 << CD->getSourceRange();
3845 HadError = true;
3846 }
3847
3848 ImplicitExceptionSpecification Spec(Context);
3849 bool Const;
3850 llvm::tie(Spec, Const) =
3851 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3852
3853 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3854 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3855 *ExceptionType = Context.getFunctionType(
3856 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3857
3858 // Check for parameter type matching.
3859 // This is a copy ctor so we know it's a cv-qualified reference to T.
3860 QualType ArgType = CtorType->getArgType(0);
3861 if (ArgType->getPointeeType().isVolatileQualified()) {
3862 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3863 HadError = true;
3864 }
3865 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3866 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3867 HadError = true;
3868 }
3869
Richard Smith61802452011-12-22 02:22:31 +00003870 // C++11 [dcl.fct.def.default]p2:
3871 // An explicitly-defaulted function may be declared constexpr only if it
3872 // would have been implicitly declared as constexpr,
3873 if (CD->isConstexpr()) {
3874 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3875 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3876 << CXXCopyConstructor;
3877 HadError = true;
3878 }
3879 }
3880 // and may have an explicit exception-specification only if it is compatible
3881 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003882 if (CtorType->hasExceptionSpec()) {
3883 if (CheckEquivalentExceptionSpec(
3884 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003885 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003886 PDiag(),
3887 ExceptionType, SourceLocation(),
3888 CtorType, CD->getLocation())) {
3889 HadError = true;
3890 }
Richard Smith61802452011-12-22 02:22:31 +00003891 }
3892
3893 // If a function is explicitly defaulted on its first declaration,
3894 if (First) {
3895 // -- it is implicitly considered to be constexpr if the implicit
3896 // definition would be,
3897 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3898
3899 // -- it is implicitly considered to have the same
3900 // exception-specification as if it had been implicitly declared, and
3901 //
3902 // FIXME: a compatible, but different, explicit exception specification
3903 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003904 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003905
3906 // -- [...] it shall have the same parameter type as if it had been
3907 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003908 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3909 }
3910
3911 if (HadError) {
3912 CD->setInvalidDecl();
3913 return;
3914 }
3915
Sean Huntc32d6842011-10-11 04:55:36 +00003916 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003917 if (First) {
3918 CD->setDeletedAsWritten();
3919 } else {
3920 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003921 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003922 CD->setInvalidDecl();
3923 }
Sean Huntca46d132011-05-12 03:51:48 +00003924 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003925}
Sean Hunt001cad92011-05-10 00:49:42 +00003926
Sean Hunt2b188082011-05-14 05:23:28 +00003927void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3928 assert(MD->isExplicitlyDefaulted());
3929
3930 // Whether this was the first-declared instance of the operator
3931 bool First = MD == MD->getCanonicalDecl();
3932
3933 bool HadError = false;
3934 if (MD->getNumParams() != 1) {
3935 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3936 << MD->getSourceRange();
3937 HadError = true;
3938 }
3939
3940 QualType ReturnType =
3941 MD->getType()->getAs<FunctionType>()->getResultType();
3942 if (!ReturnType->isLValueReferenceType() ||
3943 !Context.hasSameType(
3944 Context.getCanonicalType(ReturnType->getPointeeType()),
3945 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3946 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3947 HadError = true;
3948 }
3949
3950 ImplicitExceptionSpecification Spec(Context);
3951 bool Const;
3952 llvm::tie(Spec, Const) =
3953 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3954
3955 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3956 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3957 *ExceptionType = Context.getFunctionType(
3958 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3959
Sean Hunt2b188082011-05-14 05:23:28 +00003960 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003961 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003962 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003963 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003964 } else {
3965 if (ArgType->getPointeeType().isVolatileQualified()) {
3966 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3967 HadError = true;
3968 }
3969 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3970 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3971 HadError = true;
3972 }
Sean Hunt2b188082011-05-14 05:23:28 +00003973 }
Sean Huntbe631222011-05-17 20:44:43 +00003974
Sean Hunt2b188082011-05-14 05:23:28 +00003975 if (OperType->getTypeQuals()) {
3976 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3977 HadError = true;
3978 }
3979
3980 if (OperType->hasExceptionSpec()) {
3981 if (CheckEquivalentExceptionSpec(
3982 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003983 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003984 PDiag(),
3985 ExceptionType, SourceLocation(),
3986 OperType, MD->getLocation())) {
3987 HadError = true;
3988 }
Richard Smith61802452011-12-22 02:22:31 +00003989 }
3990 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00003991 // We set the declaration to have the computed exception spec here.
3992 // We duplicate the one parameter type.
3993 EPI.RefQualifier = OperType->getRefQualifier();
3994 EPI.ExtInfo = OperType->getExtInfo();
3995 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3996 }
3997
3998 if (HadError) {
3999 MD->setInvalidDecl();
4000 return;
4001 }
4002
4003 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4004 if (First) {
4005 MD->setDeletedAsWritten();
4006 } else {
4007 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004008 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004009 MD->setInvalidDecl();
4010 }
4011 }
4012}
4013
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004014void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4015 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4016
4017 // Whether this was the first-declared instance of the constructor.
4018 bool First = CD == CD->getCanonicalDecl();
4019
4020 bool HadError = false;
4021 if (CD->getNumParams() != 1) {
4022 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4023 << CD->getSourceRange();
4024 HadError = true;
4025 }
4026
4027 ImplicitExceptionSpecification Spec(
4028 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4029
4030 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4031 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4032 *ExceptionType = Context.getFunctionType(
4033 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4034
4035 // Check for parameter type matching.
4036 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4037 QualType ArgType = CtorType->getArgType(0);
4038 if (ArgType->getPointeeType().isVolatileQualified()) {
4039 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4040 HadError = true;
4041 }
4042 if (ArgType->getPointeeType().isConstQualified()) {
4043 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4044 HadError = true;
4045 }
4046
Richard Smith61802452011-12-22 02:22:31 +00004047 // C++11 [dcl.fct.def.default]p2:
4048 // An explicitly-defaulted function may be declared constexpr only if it
4049 // would have been implicitly declared as constexpr,
4050 if (CD->isConstexpr()) {
4051 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4052 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4053 << CXXMoveConstructor;
4054 HadError = true;
4055 }
4056 }
4057 // and may have an explicit exception-specification only if it is compatible
4058 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004059 if (CtorType->hasExceptionSpec()) {
4060 if (CheckEquivalentExceptionSpec(
4061 PDiag(diag::err_incorrect_defaulted_exception_spec)
4062 << CXXMoveConstructor,
4063 PDiag(),
4064 ExceptionType, SourceLocation(),
4065 CtorType, CD->getLocation())) {
4066 HadError = true;
4067 }
Richard Smith61802452011-12-22 02:22:31 +00004068 }
4069
4070 // If a function is explicitly defaulted on its first declaration,
4071 if (First) {
4072 // -- it is implicitly considered to be constexpr if the implicit
4073 // definition would be,
4074 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4075
4076 // -- it is implicitly considered to have the same
4077 // exception-specification as if it had been implicitly declared, and
4078 //
4079 // FIXME: a compatible, but different, explicit exception specification
4080 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004081 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004082
4083 // -- [...] it shall have the same parameter type as if it had been
4084 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004085 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4086 }
4087
4088 if (HadError) {
4089 CD->setInvalidDecl();
4090 return;
4091 }
4092
Sean Hunt769bb2d2011-10-11 06:43:29 +00004093 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004094 if (First) {
4095 CD->setDeletedAsWritten();
4096 } else {
4097 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4098 << CXXMoveConstructor;
4099 CD->setInvalidDecl();
4100 }
4101 }
4102}
4103
4104void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4105 assert(MD->isExplicitlyDefaulted());
4106
4107 // Whether this was the first-declared instance of the operator
4108 bool First = MD == MD->getCanonicalDecl();
4109
4110 bool HadError = false;
4111 if (MD->getNumParams() != 1) {
4112 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4113 << MD->getSourceRange();
4114 HadError = true;
4115 }
4116
4117 QualType ReturnType =
4118 MD->getType()->getAs<FunctionType>()->getResultType();
4119 if (!ReturnType->isLValueReferenceType() ||
4120 !Context.hasSameType(
4121 Context.getCanonicalType(ReturnType->getPointeeType()),
4122 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4123 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4124 HadError = true;
4125 }
4126
4127 ImplicitExceptionSpecification Spec(
4128 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4129
4130 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4131 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4132 *ExceptionType = Context.getFunctionType(
4133 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4134
4135 QualType ArgType = OperType->getArgType(0);
4136 if (!ArgType->isRValueReferenceType()) {
4137 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4138 HadError = true;
4139 } else {
4140 if (ArgType->getPointeeType().isVolatileQualified()) {
4141 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4142 HadError = true;
4143 }
4144 if (ArgType->getPointeeType().isConstQualified()) {
4145 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4146 HadError = true;
4147 }
4148 }
4149
4150 if (OperType->getTypeQuals()) {
4151 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4152 HadError = true;
4153 }
4154
4155 if (OperType->hasExceptionSpec()) {
4156 if (CheckEquivalentExceptionSpec(
4157 PDiag(diag::err_incorrect_defaulted_exception_spec)
4158 << CXXMoveAssignment,
4159 PDiag(),
4160 ExceptionType, SourceLocation(),
4161 OperType, MD->getLocation())) {
4162 HadError = true;
4163 }
Richard Smith61802452011-12-22 02:22:31 +00004164 }
4165 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004166 // We set the declaration to have the computed exception spec here.
4167 // We duplicate the one parameter type.
4168 EPI.RefQualifier = OperType->getRefQualifier();
4169 EPI.ExtInfo = OperType->getExtInfo();
4170 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4171 }
4172
4173 if (HadError) {
4174 MD->setInvalidDecl();
4175 return;
4176 }
4177
4178 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4179 if (First) {
4180 MD->setDeletedAsWritten();
4181 } else {
4182 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4183 << CXXMoveAssignment;
4184 MD->setInvalidDecl();
4185 }
4186 }
4187}
4188
Sean Huntcb45a0f2011-05-12 22:46:25 +00004189void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4190 assert(DD->isExplicitlyDefaulted());
4191
4192 // Whether this was the first-declared instance of the destructor.
4193 bool First = DD == DD->getCanonicalDecl();
4194
4195 ImplicitExceptionSpecification Spec
4196 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4197 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4198 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4199 *ExceptionType = Context.getFunctionType(
4200 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4201
4202 if (DtorType->hasExceptionSpec()) {
4203 if (CheckEquivalentExceptionSpec(
4204 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004205 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004206 PDiag(),
4207 ExceptionType, SourceLocation(),
4208 DtorType, DD->getLocation())) {
4209 DD->setInvalidDecl();
4210 return;
4211 }
Richard Smith61802452011-12-22 02:22:31 +00004212 }
4213 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004214 // We set the declaration to have the computed exception spec here.
4215 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004216 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004217 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4218 }
4219
4220 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004221 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004222 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004223 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004224 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004225 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004226 DD->setInvalidDecl();
4227 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004228 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004229}
4230
Sean Hunte16da072011-10-10 06:18:57 +00004231/// This function implements the following C++0x paragraphs:
4232/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004233/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004234bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4235 assert(!MD->isInvalidDecl());
4236 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004237 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004238 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004239 return false;
4240
Sean Hunte16da072011-10-10 06:18:57 +00004241 bool IsUnion = RD->isUnion();
4242 bool IsConstructor = false;
4243 bool IsAssignment = false;
4244 bool IsMove = false;
4245
4246 bool ConstArg = false;
4247
4248 switch (CSM) {
4249 case CXXDefaultConstructor:
4250 IsConstructor = true;
4251 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004252 case CXXCopyConstructor:
4253 IsConstructor = true;
4254 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4255 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004256 case CXXMoveConstructor:
4257 IsConstructor = true;
4258 IsMove = true;
4259 break;
Sean Hunte16da072011-10-10 06:18:57 +00004260 default:
4261 llvm_unreachable("function only currently implemented for default ctors");
4262 }
4263
4264 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004265
Sean Huntc32d6842011-10-11 04:55:36 +00004266 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004267 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004268
Sean Huntcdee3fe2011-05-11 22:34:38 +00004269 bool AllConst = true;
4270
Sean Huntcdee3fe2011-05-11 22:34:38 +00004271 // We do this because we should never actually use an anonymous
4272 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004273 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004274 return false;
4275
4276 // FIXME: We should put some diagnostic logic right into this function.
4277
Sean Huntcdee3fe2011-05-11 22:34:38 +00004278 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4279 BE = RD->bases_end();
4280 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004281 // We'll handle this one later
4282 if (BI->isVirtual())
4283 continue;
4284
Sean Huntcdee3fe2011-05-11 22:34:38 +00004285 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4286 assert(BaseDecl && "base isn't a CXXRecordDecl");
4287
Sean Hunte16da072011-10-10 06:18:57 +00004288 // Unless we have an assignment operator, the base's destructor must
4289 // be accessible and not deleted.
4290 if (!IsAssignment) {
4291 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4292 if (BaseDtor->isDeleted())
4293 return true;
4294 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4295 AR_accessible)
4296 return true;
4297 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004298
Sean Hunte16da072011-10-10 06:18:57 +00004299 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004300 // unique, accessible, non-deleted function. If we are doing
4301 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004302 if (CSM != CXXDestructor) {
4303 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004304 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004305 false);
4306 if (!SMOR->hasSuccess())
4307 return true;
4308 CXXMethodDecl *BaseMember = SMOR->getMethod();
4309 if (IsConstructor) {
4310 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4311 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4312 PDiag()) != AR_accessible)
4313 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004314
4315 // For a move operation, the corresponding operation must actually
4316 // be a move operation (and not a copy selected by overload
4317 // resolution) unless we are working on a trivially copyable class.
4318 if (IsMove && !BaseCtor->isMoveConstructor() &&
4319 !BaseDecl->isTriviallyCopyable())
4320 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004321 }
4322 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004323 }
4324
4325 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4326 BE = RD->vbases_end();
4327 BI != BE; ++BI) {
4328 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4329 assert(BaseDecl && "base isn't a CXXRecordDecl");
4330
Sean Hunte16da072011-10-10 06:18:57 +00004331 // Unless we have an assignment operator, the base's destructor must
4332 // be accessible and not deleted.
4333 if (!IsAssignment) {
4334 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4335 if (BaseDtor->isDeleted())
4336 return true;
4337 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4338 AR_accessible)
4339 return true;
4340 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004341
Sean Hunte16da072011-10-10 06:18:57 +00004342 // Finding the corresponding member in the base should lead to a
4343 // unique, accessible, non-deleted function.
4344 if (CSM != CXXDestructor) {
4345 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004346 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004347 false);
4348 if (!SMOR->hasSuccess())
4349 return true;
4350 CXXMethodDecl *BaseMember = SMOR->getMethod();
4351 if (IsConstructor) {
4352 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4353 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4354 PDiag()) != AR_accessible)
4355 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004356
4357 // For a move operation, the corresponding operation must actually
4358 // be a move operation (and not a copy selected by overload
4359 // resolution) unless we are working on a trivially copyable class.
4360 if (IsMove && !BaseCtor->isMoveConstructor() &&
4361 !BaseDecl->isTriviallyCopyable())
4362 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004363 }
4364 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004365 }
4366
4367 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4368 FE = RD->field_end();
4369 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004370 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004371 continue;
4372
Sean Huntcdee3fe2011-05-11 22:34:38 +00004373 QualType FieldType = Context.getBaseElementType(FI->getType());
4374 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004375
Sean Hunte16da072011-10-10 06:18:57 +00004376 // For a default constructor, all references must be initialized in-class
4377 // and, if a union, it must have a non-const member.
4378 if (CSM == CXXDefaultConstructor) {
4379 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4380 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004381
Sean Hunte16da072011-10-10 06:18:57 +00004382 if (IsUnion && !FieldType.isConstQualified())
4383 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004384 // For a copy constructor, data members must not be of rvalue reference
4385 // type.
4386 } else if (CSM == CXXCopyConstructor) {
4387 if (FieldType->isRValueReferenceType())
4388 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004389 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004390
4391 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004392 // For a default constructor, a const member must have a user-provided
4393 // default constructor or else be explicitly initialized.
4394 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004395 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004396 !FieldRecord->hasUserProvidedDefaultConstructor())
4397 return true;
4398
Sean Huntc32d6842011-10-11 04:55:36 +00004399 // Some additional restrictions exist on the variant members.
4400 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004401 FieldRecord->isAnonymousStructOrUnion()) {
4402 // We're okay to reuse AllConst here since we only care about the
4403 // value otherwise if we're in a union.
4404 AllConst = true;
4405
4406 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4407 UE = FieldRecord->field_end();
4408 UI != UE; ++UI) {
4409 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4410 CXXRecordDecl *UnionFieldRecord =
4411 UnionFieldType->getAsCXXRecordDecl();
4412
4413 if (!UnionFieldType.isConstQualified())
4414 AllConst = false;
4415
Sean Huntc32d6842011-10-11 04:55:36 +00004416 if (UnionFieldRecord) {
4417 // FIXME: Checking for accessibility and validity of this
4418 // destructor is technically going beyond the
4419 // standard, but this is believed to be a defect.
4420 if (!IsAssignment) {
4421 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4422 if (FieldDtor->isDeleted())
4423 return true;
4424 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4425 AR_accessible)
4426 return true;
4427 if (!FieldDtor->isTrivial())
4428 return true;
4429 }
4430
4431 if (CSM != CXXDestructor) {
4432 SpecialMemberOverloadResult *SMOR =
4433 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004434 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004435 // FIXME: Checking for accessibility and validity of this
4436 // corresponding member is technically going beyond the
4437 // standard, but this is believed to be a defect.
4438 if (!SMOR->hasSuccess())
4439 return true;
4440
4441 CXXMethodDecl *FieldMember = SMOR->getMethod();
4442 // A member of a union must have a trivial corresponding
4443 // constructor.
4444 if (!FieldMember->isTrivial())
4445 return true;
4446
4447 if (IsConstructor) {
4448 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4449 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4450 PDiag()) != AR_accessible)
4451 return true;
4452 }
4453 }
4454 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004455 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004456
Sean Huntc32d6842011-10-11 04:55:36 +00004457 // At least one member in each anonymous union must be non-const
4458 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004459 return true;
4460
4461 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004462 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004463 continue;
4464 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004465
Sean Huntc32d6842011-10-11 04:55:36 +00004466 // Unless we're doing assignment, the field's destructor must be
4467 // accessible and not deleted.
4468 if (!IsAssignment) {
4469 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4470 if (FieldDtor->isDeleted())
4471 return true;
4472 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4473 AR_accessible)
4474 return true;
4475 }
4476
Sean Hunte16da072011-10-10 06:18:57 +00004477 // Check that the corresponding member of the field is accessible,
4478 // unique, and non-deleted. We don't do this if it has an explicit
4479 // initialization when default-constructing.
4480 if (CSM != CXXDestructor &&
4481 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4482 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004483 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004484 false);
4485 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004486 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004487
4488 CXXMethodDecl *FieldMember = SMOR->getMethod();
4489 if (IsConstructor) {
4490 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4491 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4492 PDiag()) != AR_accessible)
4493 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004494
4495 // For a move operation, the corresponding operation must actually
4496 // be a move operation (and not a copy selected by overload
4497 // resolution) unless we are working on a trivially copyable class.
4498 if (IsMove && !FieldCtor->isMoveConstructor() &&
4499 !FieldRecord->isTriviallyCopyable())
4500 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004501 }
4502
4503 // We need the corresponding member of a union to be trivial so that
4504 // we can safely copy them all simultaneously.
4505 // FIXME: Note that performing the check here (where we rely on the lack
4506 // of an in-class initializer) is technically ill-formed. However, this
4507 // seems most obviously to be a bug in the standard.
4508 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004509 return true;
4510 }
Sean Hunte16da072011-10-10 06:18:57 +00004511 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4512 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4513 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004514 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004515 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004516 }
4517
Sean Hunte16da072011-10-10 06:18:57 +00004518 // We can't have all const members in a union when default-constructing,
4519 // or else they're all nonsensical garbage values that can't be changed.
4520 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004521 return true;
4522
4523 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004524}
4525
Sean Hunt7f410192011-05-14 05:23:24 +00004526bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4527 CXXRecordDecl *RD = MD->getParent();
4528 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004529 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004530 return false;
4531
Sean Hunt71a682f2011-05-18 03:41:58 +00004532 SourceLocation Loc = MD->getLocation();
4533
Sean Hunt7f410192011-05-14 05:23:24 +00004534 // Do access control from the constructor
4535 ContextRAII MethodContext(*this, MD);
4536
4537 bool Union = RD->isUnion();
4538
Sean Hunt661c67a2011-06-21 23:42:56 +00004539 unsigned ArgQuals =
4540 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4541 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004542
4543 // We do this because we should never actually use an anonymous
4544 // union's constructor.
4545 if (Union && RD->isAnonymousStructOrUnion())
4546 return false;
4547
Sean Hunt7f410192011-05-14 05:23:24 +00004548 // FIXME: We should put some diagnostic logic right into this function.
4549
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004550 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004551 // A defaulted [copy] assignment operator for class X is defined as deleted
4552 // if X has:
4553
4554 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4555 BE = RD->bases_end();
4556 BI != BE; ++BI) {
4557 // We'll handle this one later
4558 if (BI->isVirtual())
4559 continue;
4560
4561 QualType BaseType = BI->getType();
4562 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4563 assert(BaseDecl && "base isn't a CXXRecordDecl");
4564
4565 // -- a [direct base class] B that cannot be [copied] because overload
4566 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004567 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004568 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004569 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4570 0);
4571 if (!CopyOper || CopyOper->isDeleted())
4572 return true;
4573 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004574 return true;
4575 }
4576
4577 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4578 BE = RD->vbases_end();
4579 BI != BE; ++BI) {
4580 QualType BaseType = BI->getType();
4581 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4582 assert(BaseDecl && "base isn't a CXXRecordDecl");
4583
Sean Hunt7f410192011-05-14 05:23:24 +00004584 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004585 // resolution, as applied to B's [copy] assignment operator, results in
4586 // an ambiguity or a function that is deleted or inaccessible from the
4587 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004588 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4589 0);
4590 if (!CopyOper || CopyOper->isDeleted())
4591 return true;
4592 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004593 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004594 }
4595
4596 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4597 FE = RD->field_end();
4598 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004599 if (FI->isUnnamedBitfield())
4600 continue;
4601
Sean Hunt7f410192011-05-14 05:23:24 +00004602 QualType FieldType = Context.getBaseElementType(FI->getType());
4603
4604 // -- a non-static data member of reference type
4605 if (FieldType->isReferenceType())
4606 return true;
4607
4608 // -- a non-static data member of const non-class type (or array thereof)
4609 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4610 return true;
4611
4612 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4613
4614 if (FieldRecord) {
4615 // This is an anonymous union
4616 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4617 // Anonymous unions inside unions do not variant members create
4618 if (!Union) {
4619 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4620 UE = FieldRecord->field_end();
4621 UI != UE; ++UI) {
4622 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4623 CXXRecordDecl *UnionFieldRecord =
4624 UnionFieldType->getAsCXXRecordDecl();
4625
4626 // -- a variant member with a non-trivial [copy] assignment operator
4627 // and X is a union-like class
4628 if (UnionFieldRecord &&
4629 !UnionFieldRecord->hasTrivialCopyAssignment())
4630 return true;
4631 }
4632 }
4633
4634 // Don't try to initalize an anonymous union
4635 continue;
4636 // -- a variant member with a non-trivial [copy] assignment operator
4637 // and X is a union-like class
4638 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4639 return true;
4640 }
Sean Hunt7f410192011-05-14 05:23:24 +00004641
Sean Hunt661c67a2011-06-21 23:42:56 +00004642 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4643 false, 0);
4644 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004645 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004646 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004647 return true;
4648 }
4649 }
4650
4651 return false;
4652}
4653
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004654bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4655 CXXRecordDecl *RD = MD->getParent();
4656 assert(!RD->isDependentType() && "do deletion after instantiation");
4657 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4658 return false;
4659
4660 SourceLocation Loc = MD->getLocation();
4661
4662 // Do access control from the constructor
4663 ContextRAII MethodContext(*this, MD);
4664
4665 bool Union = RD->isUnion();
4666
4667 // We do this because we should never actually use an anonymous
4668 // union's constructor.
4669 if (Union && RD->isAnonymousStructOrUnion())
4670 return false;
4671
4672 // C++0x [class.copy]/20
4673 // A defaulted [move] assignment operator for class X is defined as deleted
4674 // if X has:
4675
4676 // -- for the move constructor, [...] any direct or indirect virtual base
4677 // class.
4678 if (RD->getNumVBases() != 0)
4679 return true;
4680
4681 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4682 BE = RD->bases_end();
4683 BI != BE; ++BI) {
4684
4685 QualType BaseType = BI->getType();
4686 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4687 assert(BaseDecl && "base isn't a CXXRecordDecl");
4688
4689 // -- a [direct base class] B that cannot be [moved] because overload
4690 // resolution, as applied to B's [move] assignment operator, results in
4691 // an ambiguity or a function that is deleted or inaccessible from the
4692 // assignment operator
4693 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4694 if (!MoveOper || MoveOper->isDeleted())
4695 return true;
4696 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4697 return true;
4698
4699 // -- for the move assignment operator, a [direct base class] with a type
4700 // that does not have a move assignment operator and is not trivially
4701 // copyable.
4702 if (!MoveOper->isMoveAssignmentOperator() &&
4703 !BaseDecl->isTriviallyCopyable())
4704 return true;
4705 }
4706
4707 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4708 FE = RD->field_end();
4709 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004710 if (FI->isUnnamedBitfield())
4711 continue;
4712
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004713 QualType FieldType = Context.getBaseElementType(FI->getType());
4714
4715 // -- a non-static data member of reference type
4716 if (FieldType->isReferenceType())
4717 return true;
4718
4719 // -- a non-static data member of const non-class type (or array thereof)
4720 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4721 return true;
4722
4723 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4724
4725 if (FieldRecord) {
4726 // This is an anonymous union
4727 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4728 // Anonymous unions inside unions do not variant members create
4729 if (!Union) {
4730 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4731 UE = FieldRecord->field_end();
4732 UI != UE; ++UI) {
4733 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4734 CXXRecordDecl *UnionFieldRecord =
4735 UnionFieldType->getAsCXXRecordDecl();
4736
4737 // -- a variant member with a non-trivial [move] assignment operator
4738 // and X is a union-like class
4739 if (UnionFieldRecord &&
4740 !UnionFieldRecord->hasTrivialMoveAssignment())
4741 return true;
4742 }
4743 }
4744
4745 // Don't try to initalize an anonymous union
4746 continue;
4747 // -- a variant member with a non-trivial [move] assignment operator
4748 // and X is a union-like class
4749 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4750 return true;
4751 }
4752
4753 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4754 if (!MoveOper || MoveOper->isDeleted())
4755 return true;
4756 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4757 return true;
4758
4759 // -- for the move assignment operator, a [non-static data member] with a
4760 // type that does not have a move assignment operator and is not
4761 // trivially copyable.
4762 if (!MoveOper->isMoveAssignmentOperator() &&
4763 !FieldRecord->isTriviallyCopyable())
4764 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004765 }
Sean Hunt7f410192011-05-14 05:23:24 +00004766 }
4767
4768 return false;
4769}
4770
Sean Huntcb45a0f2011-05-12 22:46:25 +00004771bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4772 CXXRecordDecl *RD = DD->getParent();
4773 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004774 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004775 return false;
4776
Sean Hunt71a682f2011-05-18 03:41:58 +00004777 SourceLocation Loc = DD->getLocation();
4778
Sean Huntcb45a0f2011-05-12 22:46:25 +00004779 // Do access control from the destructor
4780 ContextRAII CtorContext(*this, DD);
4781
4782 bool Union = RD->isUnion();
4783
Sean Hunt49634cf2011-05-13 06:10:58 +00004784 // We do this because we should never actually use an anonymous
4785 // union's destructor.
4786 if (Union && RD->isAnonymousStructOrUnion())
4787 return false;
4788
Sean Huntcb45a0f2011-05-12 22:46:25 +00004789 // C++0x [class.dtor]p5
4790 // A defaulted destructor for a class X is defined as deleted if:
4791 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4792 BE = RD->bases_end();
4793 BI != BE; ++BI) {
4794 // We'll handle this one later
4795 if (BI->isVirtual())
4796 continue;
4797
4798 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4799 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4800 assert(BaseDtor && "base has no destructor");
4801
4802 // -- any direct or virtual base class has a deleted destructor or
4803 // a destructor that is inaccessible from the defaulted destructor
4804 if (BaseDtor->isDeleted())
4805 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004806 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004807 AR_accessible)
4808 return true;
4809 }
4810
4811 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4812 BE = RD->vbases_end();
4813 BI != BE; ++BI) {
4814 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4815 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4816 assert(BaseDtor && "base has no destructor");
4817
4818 // -- any direct or virtual base class has a deleted destructor or
4819 // a destructor that is inaccessible from the defaulted destructor
4820 if (BaseDtor->isDeleted())
4821 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004822 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004823 AR_accessible)
4824 return true;
4825 }
4826
4827 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4828 FE = RD->field_end();
4829 FI != FE; ++FI) {
4830 QualType FieldType = Context.getBaseElementType(FI->getType());
4831 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4832 if (FieldRecord) {
4833 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4834 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4835 UE = FieldRecord->field_end();
4836 UI != UE; ++UI) {
4837 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4838 CXXRecordDecl *UnionFieldRecord =
4839 UnionFieldType->getAsCXXRecordDecl();
4840
4841 // -- X is a union-like class that has a variant member with a non-
4842 // trivial destructor.
4843 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4844 return true;
4845 }
4846 // Technically we are supposed to do this next check unconditionally.
4847 // But that makes absolutely no sense.
4848 } else {
4849 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4850
4851 // -- any of the non-static data members has class type M (or array
4852 // thereof) and M has a deleted destructor or a destructor that is
4853 // inaccessible from the defaulted destructor
4854 if (FieldDtor->isDeleted())
4855 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004856 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004857 AR_accessible)
4858 return true;
4859
4860 // -- X is a union-like class that has a variant member with a non-
4861 // trivial destructor.
4862 if (Union && !FieldDtor->isTrivial())
4863 return true;
4864 }
4865 }
4866 }
4867
4868 if (DD->isVirtual()) {
4869 FunctionDecl *OperatorDelete = 0;
4870 DeclarationName Name =
4871 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004872 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004873 false))
4874 return true;
4875 }
4876
4877
4878 return false;
4879}
4880
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004881/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004882namespace {
4883 struct FindHiddenVirtualMethodData {
4884 Sema *S;
4885 CXXMethodDecl *Method;
4886 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004887 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004888 };
4889}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004890
4891/// \brief Member lookup function that determines whether a given C++
4892/// method overloads virtual methods in a base class without overriding any,
4893/// to be used with CXXRecordDecl::lookupInBases().
4894static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4895 CXXBasePath &Path,
4896 void *UserData) {
4897 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4898
4899 FindHiddenVirtualMethodData &Data
4900 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4901
4902 DeclarationName Name = Data.Method->getDeclName();
4903 assert(Name.getNameKind() == DeclarationName::Identifier);
4904
4905 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004906 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004907 for (Path.Decls = BaseRecord->lookup(Name);
4908 Path.Decls.first != Path.Decls.second;
4909 ++Path.Decls.first) {
4910 NamedDecl *D = *Path.Decls.first;
4911 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004912 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004913 foundSameNameMethod = true;
4914 // Interested only in hidden virtual methods.
4915 if (!MD->isVirtual())
4916 continue;
4917 // If the method we are checking overrides a method from its base
4918 // don't warn about the other overloaded methods.
4919 if (!Data.S->IsOverload(Data.Method, MD, false))
4920 return true;
4921 // Collect the overload only if its hidden.
4922 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4923 overloadedMethods.push_back(MD);
4924 }
4925 }
4926
4927 if (foundSameNameMethod)
4928 Data.OverloadedMethods.append(overloadedMethods.begin(),
4929 overloadedMethods.end());
4930 return foundSameNameMethod;
4931}
4932
4933/// \brief See if a method overloads virtual methods in a base class without
4934/// overriding any.
4935void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4936 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004937 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004938 return;
4939 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4940 return;
4941
4942 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4943 /*bool RecordPaths=*/false,
4944 /*bool DetectVirtual=*/false);
4945 FindHiddenVirtualMethodData Data;
4946 Data.Method = MD;
4947 Data.S = this;
4948
4949 // Keep the base methods that were overriden or introduced in the subclass
4950 // by 'using' in a set. A base method not in this set is hidden.
4951 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4952 res.first != res.second; ++res.first) {
4953 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4954 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4955 E = MD->end_overridden_methods();
4956 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004957 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004958 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4959 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004960 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004961 }
4962
4963 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4964 !Data.OverloadedMethods.empty()) {
4965 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4966 << MD << (Data.OverloadedMethods.size() > 1);
4967
4968 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4969 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4970 Diag(overloadedMD->getLocation(),
4971 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4972 }
4973 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004974}
4975
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004976void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004977 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004978 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004979 SourceLocation RBrac,
4980 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004981 if (!TagDecl)
4982 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004983
Douglas Gregor42af25f2009-05-11 19:58:34 +00004984 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004985
David Blaikie77b6de02011-09-22 02:58:26 +00004986 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004987 // strict aliasing violation!
4988 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004989 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004990
Douglas Gregor23c94db2010-07-02 17:43:08 +00004991 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004992 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004993}
4994
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004995/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4996/// special functions, such as the default constructor, copy
4997/// constructor, or destructor, to the given C++ class (C++
4998/// [special]p1). This routine can only be executed just before the
4999/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005000void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005001 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005002 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005003
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005004 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005005 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005006
Richard Smithb701d3d2011-12-24 21:56:24 +00005007 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5008 ++ASTContext::NumImplicitMoveConstructors;
5009
Douglas Gregora376d102010-07-02 21:50:04 +00005010 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5011 ++ASTContext::NumImplicitCopyAssignmentOperators;
5012
5013 // If we have a dynamic class, then the copy assignment operator may be
5014 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5015 // it shows up in the right place in the vtable and that we diagnose
5016 // problems with the implicit exception specification.
5017 if (ClassDecl->isDynamicClass())
5018 DeclareImplicitCopyAssignment(ClassDecl);
5019 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005020
Richard Smithb701d3d2011-12-24 21:56:24 +00005021 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5022 ++ASTContext::NumImplicitMoveAssignmentOperators;
5023
5024 // Likewise for the move assignment operator.
5025 if (ClassDecl->isDynamicClass())
5026 DeclareImplicitMoveAssignment(ClassDecl);
5027 }
5028
Douglas Gregor4923aa22010-07-02 20:37:36 +00005029 if (!ClassDecl->hasUserDeclaredDestructor()) {
5030 ++ASTContext::NumImplicitDestructors;
5031
5032 // If we have a dynamic class, then the destructor may be virtual, so we
5033 // have to declare the destructor immediately. This ensures that, e.g., it
5034 // shows up in the right place in the vtable and that we diagnose problems
5035 // with the implicit exception specification.
5036 if (ClassDecl->isDynamicClass())
5037 DeclareImplicitDestructor(ClassDecl);
5038 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005039}
5040
Francois Pichet8387e2a2011-04-22 22:18:13 +00005041void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5042 if (!D)
5043 return;
5044
5045 int NumParamList = D->getNumTemplateParameterLists();
5046 for (int i = 0; i < NumParamList; i++) {
5047 TemplateParameterList* Params = D->getTemplateParameterList(i);
5048 for (TemplateParameterList::iterator Param = Params->begin(),
5049 ParamEnd = Params->end();
5050 Param != ParamEnd; ++Param) {
5051 NamedDecl *Named = cast<NamedDecl>(*Param);
5052 if (Named->getDeclName()) {
5053 S->AddDecl(Named);
5054 IdResolver.AddDecl(Named);
5055 }
5056 }
5057 }
5058}
5059
John McCalld226f652010-08-21 09:40:31 +00005060void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005061 if (!D)
5062 return;
5063
5064 TemplateParameterList *Params = 0;
5065 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5066 Params = Template->getTemplateParameters();
5067 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5068 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5069 Params = PartialSpec->getTemplateParameters();
5070 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005071 return;
5072
Douglas Gregor6569d682009-05-27 23:11:45 +00005073 for (TemplateParameterList::iterator Param = Params->begin(),
5074 ParamEnd = Params->end();
5075 Param != ParamEnd; ++Param) {
5076 NamedDecl *Named = cast<NamedDecl>(*Param);
5077 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005078 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005079 IdResolver.AddDecl(Named);
5080 }
5081 }
5082}
5083
John McCalld226f652010-08-21 09:40:31 +00005084void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005085 if (!RecordD) return;
5086 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005087 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005088 PushDeclContext(S, Record);
5089}
5090
John McCalld226f652010-08-21 09:40:31 +00005091void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005092 if (!RecordD) return;
5093 PopDeclContext();
5094}
5095
Douglas Gregor72b505b2008-12-16 21:30:33 +00005096/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5097/// parsing a top-level (non-nested) C++ class, and we are now
5098/// parsing those parts of the given Method declaration that could
5099/// not be parsed earlier (C++ [class.mem]p2), such as default
5100/// arguments. This action should enter the scope of the given
5101/// Method declaration as if we had just parsed the qualified method
5102/// name. However, it should not bring the parameters into scope;
5103/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005104void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005105}
5106
5107/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5108/// C++ method declaration. We're (re-)introducing the given
5109/// function parameter into scope for use in parsing later parts of
5110/// the method declaration. For example, we could see an
5111/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005112void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005113 if (!ParamD)
5114 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005115
John McCalld226f652010-08-21 09:40:31 +00005116 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005117
5118 // If this parameter has an unparsed default argument, clear it out
5119 // to make way for the parsed default argument.
5120 if (Param->hasUnparsedDefaultArg())
5121 Param->setDefaultArg(0);
5122
John McCalld226f652010-08-21 09:40:31 +00005123 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005124 if (Param->getDeclName())
5125 IdResolver.AddDecl(Param);
5126}
5127
5128/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5129/// processing the delayed method declaration for Method. The method
5130/// declaration is now considered finished. There may be a separate
5131/// ActOnStartOfFunctionDef action later (not necessarily
5132/// immediately!) for this method, if it was also defined inside the
5133/// class body.
John McCalld226f652010-08-21 09:40:31 +00005134void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005135 if (!MethodD)
5136 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005137
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005138 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005139
John McCalld226f652010-08-21 09:40:31 +00005140 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005141
5142 // Now that we have our default arguments, check the constructor
5143 // again. It could produce additional diagnostics or affect whether
5144 // the class has implicitly-declared destructors, among other
5145 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005146 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5147 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005148
5149 // Check the default arguments, which we may have added.
5150 if (!Method->isInvalidDecl())
5151 CheckCXXDefaultArguments(Method);
5152}
5153
Douglas Gregor42a552f2008-11-05 20:51:48 +00005154/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005155/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005156/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005157/// emit diagnostics and set the invalid bit to true. In any case, the type
5158/// will be updated to reflect a well-formed type for the constructor and
5159/// returned.
5160QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005161 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005162 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005163
5164 // C++ [class.ctor]p3:
5165 // A constructor shall not be virtual (10.3) or static (9.4). A
5166 // constructor can be invoked for a const, volatile or const
5167 // volatile object. A constructor shall not be declared const,
5168 // volatile, or const volatile (9.3.2).
5169 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005170 if (!D.isInvalidType())
5171 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5172 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5173 << SourceRange(D.getIdentifierLoc());
5174 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005175 }
John McCalld931b082010-08-26 03:08:43 +00005176 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005177 if (!D.isInvalidType())
5178 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5179 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5180 << SourceRange(D.getIdentifierLoc());
5181 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005182 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005183 }
Mike Stump1eb44332009-09-09 15:08:12 +00005184
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005185 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005186 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005187 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005188 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5189 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005190 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005191 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5192 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005193 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005194 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5195 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005196 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005197 }
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Douglas Gregorc938c162011-01-26 05:01:58 +00005199 // C++0x [class.ctor]p4:
5200 // A constructor shall not be declared with a ref-qualifier.
5201 if (FTI.hasRefQualifier()) {
5202 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5203 << FTI.RefQualifierIsLValueRef
5204 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5205 D.setInvalidType();
5206 }
5207
Douglas Gregor42a552f2008-11-05 20:51:48 +00005208 // Rebuild the function type "R" without any type qualifiers (in
5209 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005210 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005211 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005212 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5213 return R;
5214
5215 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5216 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005217 EPI.RefQualifier = RQ_None;
5218
Chris Lattner65401802009-04-25 08:28:21 +00005219 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005220 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005221}
5222
Douglas Gregor72b505b2008-12-16 21:30:33 +00005223/// CheckConstructor - Checks a fully-formed constructor for
5224/// well-formedness, issuing any diagnostics required. Returns true if
5225/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005226void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005227 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005228 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5229 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005230 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005231
5232 // C++ [class.copy]p3:
5233 // A declaration of a constructor for a class X is ill-formed if
5234 // its first parameter is of type (optionally cv-qualified) X and
5235 // either there are no other parameters or else all other
5236 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005237 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005238 ((Constructor->getNumParams() == 1) ||
5239 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005240 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5241 Constructor->getTemplateSpecializationKind()
5242 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005243 QualType ParamType = Constructor->getParamDecl(0)->getType();
5244 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5245 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005246 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005247 const char *ConstRef
5248 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5249 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005250 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005251 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005252
5253 // FIXME: Rather that making the constructor invalid, we should endeavor
5254 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005255 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005256 }
5257 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005258}
5259
John McCall15442822010-08-04 01:04:25 +00005260/// CheckDestructor - Checks a fully-formed destructor definition for
5261/// well-formedness, issuing any diagnostics required. Returns true
5262/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005263bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005264 CXXRecordDecl *RD = Destructor->getParent();
5265
5266 if (Destructor->isVirtual()) {
5267 SourceLocation Loc;
5268
5269 if (!Destructor->isImplicit())
5270 Loc = Destructor->getLocation();
5271 else
5272 Loc = RD->getLocation();
5273
5274 // If we have a virtual destructor, look up the deallocation function
5275 FunctionDecl *OperatorDelete = 0;
5276 DeclarationName Name =
5277 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005278 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005279 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005280
5281 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005282
5283 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005284 }
Anders Carlsson37909802009-11-30 21:24:50 +00005285
5286 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005287}
5288
Mike Stump1eb44332009-09-09 15:08:12 +00005289static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005290FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5291 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5292 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005293 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005294}
5295
Douglas Gregor42a552f2008-11-05 20:51:48 +00005296/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5297/// the well-formednes of the destructor declarator @p D with type @p
5298/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005299/// emit diagnostics and set the declarator to invalid. Even if this happens,
5300/// will be updated to reflect a well-formed type for the destructor and
5301/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005302QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005303 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005304 // C++ [class.dtor]p1:
5305 // [...] A typedef-name that names a class is a class-name
5306 // (7.1.3); however, a typedef-name that names a class shall not
5307 // be used as the identifier in the declarator for a destructor
5308 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005309 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005310 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005311 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005312 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005313 else if (const TemplateSpecializationType *TST =
5314 DeclaratorType->getAs<TemplateSpecializationType>())
5315 if (TST->isTypeAlias())
5316 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5317 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005318
5319 // C++ [class.dtor]p2:
5320 // A destructor is used to destroy objects of its class type. A
5321 // destructor takes no parameters, and no return type can be
5322 // specified for it (not even void). The address of a destructor
5323 // shall not be taken. A destructor shall not be static. A
5324 // destructor can be invoked for a const, volatile or const
5325 // volatile object. A destructor shall not be declared const,
5326 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005327 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005328 if (!D.isInvalidType())
5329 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5330 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005331 << SourceRange(D.getIdentifierLoc())
5332 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5333
John McCalld931b082010-08-26 03:08:43 +00005334 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005335 }
Chris Lattner65401802009-04-25 08:28:21 +00005336 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005337 // Destructors don't have return types, but the parser will
5338 // happily parse something like:
5339 //
5340 // class X {
5341 // float ~X();
5342 // };
5343 //
5344 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005345 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5346 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5347 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005348 }
Mike Stump1eb44332009-09-09 15:08:12 +00005349
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005350 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005351 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005352 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005353 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5354 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005355 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005356 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5357 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005358 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005359 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5360 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005361 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005362 }
5363
Douglas Gregorc938c162011-01-26 05:01:58 +00005364 // C++0x [class.dtor]p2:
5365 // A destructor shall not be declared with a ref-qualifier.
5366 if (FTI.hasRefQualifier()) {
5367 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5368 << FTI.RefQualifierIsLValueRef
5369 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5370 D.setInvalidType();
5371 }
5372
Douglas Gregor42a552f2008-11-05 20:51:48 +00005373 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005374 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005375 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5376
5377 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005378 FTI.freeArgs();
5379 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005380 }
5381
Mike Stump1eb44332009-09-09 15:08:12 +00005382 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005383 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005384 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005385 D.setInvalidType();
5386 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005387
5388 // Rebuild the function type "R" without any type qualifiers or
5389 // parameters (in case any of the errors above fired) and with
5390 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005391 // types.
John McCalle23cf432010-12-14 08:05:40 +00005392 if (!D.isInvalidType())
5393 return R;
5394
Douglas Gregord92ec472010-07-01 05:10:53 +00005395 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005396 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5397 EPI.Variadic = false;
5398 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005399 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005400 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005401}
5402
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005403/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5404/// well-formednes of the conversion function declarator @p D with
5405/// type @p R. If there are any errors in the declarator, this routine
5406/// will emit diagnostics and return true. Otherwise, it will return
5407/// false. Either way, the type @p R will be updated to reflect a
5408/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005409void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005410 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005411 // C++ [class.conv.fct]p1:
5412 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005413 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005414 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005415 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005416 if (!D.isInvalidType())
5417 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5418 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5419 << SourceRange(D.getIdentifierLoc());
5420 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005421 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005422 }
John McCalla3f81372010-04-13 00:04:31 +00005423
5424 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5425
Chris Lattner6e475012009-04-25 08:35:12 +00005426 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005427 // Conversion functions don't have return types, but the parser will
5428 // happily parse something like:
5429 //
5430 // class X {
5431 // float operator bool();
5432 // };
5433 //
5434 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005435 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5436 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5437 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005438 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005439 }
5440
John McCalla3f81372010-04-13 00:04:31 +00005441 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5442
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005443 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005444 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005445 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5446
5447 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005448 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005449 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005450 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005451 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005452 D.setInvalidType();
5453 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005454
John McCalla3f81372010-04-13 00:04:31 +00005455 // Diagnose "&operator bool()" and other such nonsense. This
5456 // is actually a gcc extension which we don't support.
5457 if (Proto->getResultType() != ConvType) {
5458 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5459 << Proto->getResultType();
5460 D.setInvalidType();
5461 ConvType = Proto->getResultType();
5462 }
5463
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005464 // C++ [class.conv.fct]p4:
5465 // The conversion-type-id shall not represent a function type nor
5466 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005467 if (ConvType->isArrayType()) {
5468 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5469 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005470 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005471 } else if (ConvType->isFunctionType()) {
5472 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5473 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005474 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005475 }
5476
5477 // Rebuild the function type "R" without any parameters (in case any
5478 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005479 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005480 if (D.isInvalidType())
5481 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005482
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005483 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005484 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005485 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005486 getLangOptions().CPlusPlus0x ?
5487 diag::warn_cxx98_compat_explicit_conversion_functions :
5488 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005489 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005490}
5491
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005492/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5493/// the declaration of the given C++ conversion function. This routine
5494/// is responsible for recording the conversion function in the C++
5495/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005496Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005497 assert(Conversion && "Expected to receive a conversion function declaration");
5498
Douglas Gregor9d350972008-12-12 08:25:50 +00005499 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005500
5501 // Make sure we aren't redeclaring the conversion function.
5502 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005503
5504 // C++ [class.conv.fct]p1:
5505 // [...] A conversion function is never used to convert a
5506 // (possibly cv-qualified) object to the (possibly cv-qualified)
5507 // same object type (or a reference to it), to a (possibly
5508 // cv-qualified) base class of that type (or a reference to it),
5509 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005510 // FIXME: Suppress this warning if the conversion function ends up being a
5511 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005512 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005513 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005514 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005515 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005516 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5517 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005518 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005519 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005520 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5521 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005522 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005523 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005524 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005525 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005526 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005527 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005528 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005529 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005530 }
5531
Douglas Gregore80622f2010-09-29 04:25:11 +00005532 if (FunctionTemplateDecl *ConversionTemplate
5533 = Conversion->getDescribedFunctionTemplate())
5534 return ConversionTemplate;
5535
John McCalld226f652010-08-21 09:40:31 +00005536 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005537}
5538
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005539//===----------------------------------------------------------------------===//
5540// Namespace Handling
5541//===----------------------------------------------------------------------===//
5542
John McCallea318642010-08-26 09:15:37 +00005543
5544
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005545/// ActOnStartNamespaceDef - This is called at the start of a namespace
5546/// definition.
John McCalld226f652010-08-21 09:40:31 +00005547Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005548 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005549 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005550 SourceLocation IdentLoc,
5551 IdentifierInfo *II,
5552 SourceLocation LBrace,
5553 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005554 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5555 // For anonymous namespace, take the location of the left brace.
5556 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005557 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005558 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005559 bool IsStd = false;
5560 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005561 Scope *DeclRegionScope = NamespcScope->getParent();
5562
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005563 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005564 if (II) {
5565 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005566 // The identifier in an original-namespace-definition shall not
5567 // have been previously defined in the declarative region in
5568 // which the original-namespace-definition appears. The
5569 // identifier in an original-namespace-definition is the name of
5570 // the namespace. Subsequently in that declarative region, it is
5571 // treated as an original-namespace-name.
5572 //
5573 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005574 // look through using directives, just look for any ordinary names.
5575
5576 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005577 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5578 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005579 NamedDecl *PrevDecl = 0;
5580 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005581 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005582 R.first != R.second; ++R.first) {
5583 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5584 PrevDecl = *R.first;
5585 break;
5586 }
5587 }
5588
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005589 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5590
5591 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005592 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005593 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005594 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005595 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005596 // The user probably just forgot the 'inline', so suggest that it
5597 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005598 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005599 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5600 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005601 Diag(Loc, diag::err_inline_namespace_mismatch)
5602 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005603 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005604 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5605
5606 IsInline = PrevNS->isInline();
5607 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005608 } else if (PrevDecl) {
5609 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005610 Diag(Loc, diag::err_redefinition_different_kind)
5611 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005612 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005613 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005614 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005615 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005616 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005617 // This is the first "real" definition of the namespace "std", so update
5618 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005619 PrevNS = getStdNamespace();
5620 IsStd = true;
5621 AddToKnown = !IsInline;
5622 } else {
5623 // We've seen this namespace for the first time.
5624 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005625 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005626 } else {
John McCall9aeed322009-10-01 00:25:31 +00005627 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005628
5629 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005630 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005631 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005632 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005633 } else {
5634 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005635 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005636 }
5637
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005638 if (PrevNS && IsInline != PrevNS->isInline()) {
5639 // inline-ness must match
5640 Diag(Loc, diag::err_inline_namespace_mismatch)
5641 << IsInline;
5642 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005643
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005644 // Recover by ignoring the new namespace's inline status.
5645 IsInline = PrevNS->isInline();
5646 }
5647 }
5648
5649 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5650 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005651 if (IsInvalid)
5652 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005653
5654 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005655
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005656 // FIXME: Should we be merging attributes?
5657 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5658 PushNamespaceVisibilityAttr(Attr);
5659
5660 if (IsStd)
5661 StdNamespace = Namespc;
5662 if (AddToKnown)
5663 KnownNamespaces[Namespc] = false;
5664
5665 if (II) {
5666 PushOnScopeChains(Namespc, DeclRegionScope);
5667 } else {
5668 // Link the anonymous namespace into its parent.
5669 DeclContext *Parent = CurContext->getRedeclContext();
5670 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5671 TU->setAnonymousNamespace(Namespc);
5672 } else {
5673 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005674 }
John McCall9aeed322009-10-01 00:25:31 +00005675
Douglas Gregora4181472010-03-24 00:46:35 +00005676 CurContext->addDecl(Namespc);
5677
John McCall9aeed322009-10-01 00:25:31 +00005678 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5679 // behaves as if it were replaced by
5680 // namespace unique { /* empty body */ }
5681 // using namespace unique;
5682 // namespace unique { namespace-body }
5683 // where all occurrences of 'unique' in a translation unit are
5684 // replaced by the same identifier and this identifier differs
5685 // from all other identifiers in the entire program.
5686
5687 // We just create the namespace with an empty name and then add an
5688 // implicit using declaration, just like the standard suggests.
5689 //
5690 // CodeGen enforces the "universally unique" aspect by giving all
5691 // declarations semantically contained within an anonymous
5692 // namespace internal linkage.
5693
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005694 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005695 UsingDirectiveDecl* UD
5696 = UsingDirectiveDecl::Create(Context, CurContext,
5697 /* 'using' */ LBrace,
5698 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005699 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005700 /* identifier */ SourceLocation(),
5701 Namespc,
5702 /* Ancestor */ CurContext);
5703 UD->setImplicit();
5704 CurContext->addDecl(UD);
5705 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005706 }
5707
5708 // Although we could have an invalid decl (i.e. the namespace name is a
5709 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005710 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5711 // for the namespace has the declarations that showed up in that particular
5712 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005713 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005714 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005715}
5716
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005717/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5718/// is a namespace alias, returns the namespace it points to.
5719static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5720 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5721 return AD->getNamespace();
5722 return dyn_cast_or_null<NamespaceDecl>(D);
5723}
5724
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005725/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5726/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005727void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005728 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5729 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005730 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005731 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005732 if (Namespc->hasAttr<VisibilityAttr>())
5733 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005734}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005735
John McCall384aff82010-08-25 07:42:41 +00005736CXXRecordDecl *Sema::getStdBadAlloc() const {
5737 return cast_or_null<CXXRecordDecl>(
5738 StdBadAlloc.get(Context.getExternalSource()));
5739}
5740
5741NamespaceDecl *Sema::getStdNamespace() const {
5742 return cast_or_null<NamespaceDecl>(
5743 StdNamespace.get(Context.getExternalSource()));
5744}
5745
Douglas Gregor66992202010-06-29 17:53:46 +00005746/// \brief Retrieve the special "std" namespace, which may require us to
5747/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005748NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005749 if (!StdNamespace) {
5750 // The "std" namespace has not yet been defined, so build one implicitly.
5751 StdNamespace = NamespaceDecl::Create(Context,
5752 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005753 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005754 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005755 &PP.getIdentifierTable().get("std"),
5756 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005757 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005758 }
5759
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005760 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005761}
5762
Douglas Gregor9172aa62011-03-26 22:25:30 +00005763/// \brief Determine whether a using statement is in a context where it will be
5764/// apply in all contexts.
5765static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5766 switch (CurContext->getDeclKind()) {
5767 case Decl::TranslationUnit:
5768 return true;
5769 case Decl::LinkageSpec:
5770 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5771 default:
5772 return false;
5773 }
5774}
5775
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005776namespace {
5777
5778// Callback to only accept typo corrections that are namespaces.
5779class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5780 public:
5781 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5782 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5783 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5784 }
5785 return false;
5786 }
5787};
5788
5789}
5790
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005791static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5792 CXXScopeSpec &SS,
5793 SourceLocation IdentLoc,
5794 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005795 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005796 R.clear();
5797 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005798 R.getLookupKind(), Sc, &SS,
5799 &Validator)) {
5800 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5801 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5802 if (DeclContext *DC = S.computeDeclContext(SS, false))
5803 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5804 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5805 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5806 else
5807 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5808 << Ident << CorrectedQuotedStr
5809 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005810
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005811 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5812 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005813
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005814 Ident = Corrected.getCorrectionAsIdentifierInfo();
5815 R.addDecl(Corrected.getCorrectionDecl());
5816 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005817 }
5818 return false;
5819}
5820
John McCalld226f652010-08-21 09:40:31 +00005821Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005822 SourceLocation UsingLoc,
5823 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005824 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005825 SourceLocation IdentLoc,
5826 IdentifierInfo *NamespcName,
5827 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005828 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5829 assert(NamespcName && "Invalid NamespcName.");
5830 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005831
5832 // This can only happen along a recovery path.
5833 while (S->getFlags() & Scope::TemplateParamScope)
5834 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005835 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005836
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005837 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005838 NestedNameSpecifier *Qualifier = 0;
5839 if (SS.isSet())
5840 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5841
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005842 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005843 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5844 LookupParsedName(R, S, &SS);
5845 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005846 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005847
Douglas Gregor66992202010-06-29 17:53:46 +00005848 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005849 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005850 // Allow "using namespace std;" or "using namespace ::std;" even if
5851 // "std" hasn't been defined yet, for GCC compatibility.
5852 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5853 NamespcName->isStr("std")) {
5854 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005855 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005856 R.resolveKind();
5857 }
5858 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005859 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005860 }
5861
John McCallf36e02d2009-10-09 21:13:30 +00005862 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005863 NamedDecl *Named = R.getFoundDecl();
5864 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5865 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005866 // C++ [namespace.udir]p1:
5867 // A using-directive specifies that the names in the nominated
5868 // namespace can be used in the scope in which the
5869 // using-directive appears after the using-directive. During
5870 // unqualified name lookup (3.4.1), the names appear as if they
5871 // were declared in the nearest enclosing namespace which
5872 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005873 // namespace. [Note: in this context, "contains" means "contains
5874 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005875
5876 // Find enclosing context containing both using-directive and
5877 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005878 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005879 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5880 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5881 CommonAncestor = CommonAncestor->getParent();
5882
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005883 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005884 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005885 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005886
Douglas Gregor9172aa62011-03-26 22:25:30 +00005887 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005888 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005889 Diag(IdentLoc, diag::warn_using_directive_in_header);
5890 }
5891
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005892 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005893 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005894 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005895 }
5896
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005897 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005898 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005899}
5900
5901void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5902 // If scope has associated entity, then using directive is at namespace
5903 // or translation unit scope. We add UsingDirectiveDecls, into
5904 // it's lookup structure.
5905 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005906 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005907 else
5908 // Otherwise it is block-sope. using-directives will affect lookup
5909 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005910 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005911}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005912
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005913
John McCalld226f652010-08-21 09:40:31 +00005914Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005915 AccessSpecifier AS,
5916 bool HasUsingKeyword,
5917 SourceLocation UsingLoc,
5918 CXXScopeSpec &SS,
5919 UnqualifiedId &Name,
5920 AttributeList *AttrList,
5921 bool IsTypeName,
5922 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005923 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005924
Douglas Gregor12c118a2009-11-04 16:30:06 +00005925 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005926 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005927 case UnqualifiedId::IK_Identifier:
5928 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005929 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005930 case UnqualifiedId::IK_ConversionFunctionId:
5931 break;
5932
5933 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005934 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005935 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00005936 Diag(Name.getSourceRange().getBegin(),
5937 getLangOptions().CPlusPlus0x ?
5938 diag::warn_cxx98_compat_using_decl_constructor :
5939 diag::err_using_decl_constructor)
5940 << SS.getRange();
5941
John McCall604e7f12009-12-08 07:46:18 +00005942 if (getLangOptions().CPlusPlus0x) break;
5943
John McCalld226f652010-08-21 09:40:31 +00005944 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005945
5946 case UnqualifiedId::IK_DestructorName:
5947 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5948 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005949 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005950
5951 case UnqualifiedId::IK_TemplateId:
5952 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5953 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005954 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005955 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005956
5957 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5958 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005959 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005960 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005961
John McCall60fa3cf2009-12-11 02:10:03 +00005962 // Warn about using declarations.
5963 // TODO: store that the declaration was written without 'using' and
5964 // talk about access decls instead of using decls in the
5965 // diagnostics.
5966 if (!HasUsingKeyword) {
5967 UsingLoc = Name.getSourceRange().getBegin();
5968
5969 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005970 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005971 }
5972
Douglas Gregor56c04582010-12-16 00:46:58 +00005973 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5974 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5975 return 0;
5976
John McCall9488ea12009-11-17 05:59:44 +00005977 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005978 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005979 /* IsInstantiation */ false,
5980 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005981 if (UD)
5982 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005983
John McCalld226f652010-08-21 09:40:31 +00005984 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005985}
5986
Douglas Gregor09acc982010-07-07 23:08:52 +00005987/// \brief Determine whether a using declaration considers the given
5988/// declarations as "equivalent", e.g., if they are redeclarations of
5989/// the same entity or are both typedefs of the same type.
5990static bool
5991IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5992 bool &SuppressRedeclaration) {
5993 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5994 SuppressRedeclaration = false;
5995 return true;
5996 }
5997
Richard Smith162e1c12011-04-15 14:24:37 +00005998 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5999 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006000 SuppressRedeclaration = true;
6001 return Context.hasSameType(TD1->getUnderlyingType(),
6002 TD2->getUnderlyingType());
6003 }
6004
6005 return false;
6006}
6007
6008
John McCall9f54ad42009-12-10 09:41:52 +00006009/// Determines whether to create a using shadow decl for a particular
6010/// decl, given the set of decls existing prior to this using lookup.
6011bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6012 const LookupResult &Previous) {
6013 // Diagnose finding a decl which is not from a base class of the
6014 // current class. We do this now because there are cases where this
6015 // function will silently decide not to build a shadow decl, which
6016 // will pre-empt further diagnostics.
6017 //
6018 // We don't need to do this in C++0x because we do the check once on
6019 // the qualifier.
6020 //
6021 // FIXME: diagnose the following if we care enough:
6022 // struct A { int foo; };
6023 // struct B : A { using A::foo; };
6024 // template <class T> struct C : A {};
6025 // template <class T> struct D : C<T> { using B::foo; } // <---
6026 // This is invalid (during instantiation) in C++03 because B::foo
6027 // resolves to the using decl in B, which is not a base class of D<T>.
6028 // We can't diagnose it immediately because C<T> is an unknown
6029 // specialization. The UsingShadowDecl in D<T> then points directly
6030 // to A::foo, which will look well-formed when we instantiate.
6031 // The right solution is to not collapse the shadow-decl chain.
6032 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6033 DeclContext *OrigDC = Orig->getDeclContext();
6034
6035 // Handle enums and anonymous structs.
6036 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6037 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6038 while (OrigRec->isAnonymousStructOrUnion())
6039 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6040
6041 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6042 if (OrigDC == CurContext) {
6043 Diag(Using->getLocation(),
6044 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006045 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006046 Diag(Orig->getLocation(), diag::note_using_decl_target);
6047 return true;
6048 }
6049
Douglas Gregordc355712011-02-25 00:36:19 +00006050 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006051 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006052 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006053 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006054 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006055 Diag(Orig->getLocation(), diag::note_using_decl_target);
6056 return true;
6057 }
6058 }
6059
6060 if (Previous.empty()) return false;
6061
6062 NamedDecl *Target = Orig;
6063 if (isa<UsingShadowDecl>(Target))
6064 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6065
John McCalld7533ec2009-12-11 02:33:26 +00006066 // If the target happens to be one of the previous declarations, we
6067 // don't have a conflict.
6068 //
6069 // FIXME: but we might be increasing its access, in which case we
6070 // should redeclare it.
6071 NamedDecl *NonTag = 0, *Tag = 0;
6072 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6073 I != E; ++I) {
6074 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006075 bool Result;
6076 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6077 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006078
6079 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6080 }
6081
John McCall9f54ad42009-12-10 09:41:52 +00006082 if (Target->isFunctionOrFunctionTemplate()) {
6083 FunctionDecl *FD;
6084 if (isa<FunctionTemplateDecl>(Target))
6085 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6086 else
6087 FD = cast<FunctionDecl>(Target);
6088
6089 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006090 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006091 case Ovl_Overload:
6092 return false;
6093
6094 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006095 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006096 break;
6097
6098 // We found a decl with the exact signature.
6099 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006100 // If we're in a record, we want to hide the target, so we
6101 // return true (without a diagnostic) to tell the caller not to
6102 // build a shadow decl.
6103 if (CurContext->isRecord())
6104 return true;
6105
6106 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006107 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006108 break;
6109 }
6110
6111 Diag(Target->getLocation(), diag::note_using_decl_target);
6112 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6113 return true;
6114 }
6115
6116 // Target is not a function.
6117
John McCall9f54ad42009-12-10 09:41:52 +00006118 if (isa<TagDecl>(Target)) {
6119 // No conflict between a tag and a non-tag.
6120 if (!Tag) return false;
6121
John McCall41ce66f2009-12-10 19:51:03 +00006122 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006123 Diag(Target->getLocation(), diag::note_using_decl_target);
6124 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6125 return true;
6126 }
6127
6128 // No conflict between a tag and a non-tag.
6129 if (!NonTag) return false;
6130
John McCall41ce66f2009-12-10 19:51:03 +00006131 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006132 Diag(Target->getLocation(), diag::note_using_decl_target);
6133 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6134 return true;
6135}
6136
John McCall9488ea12009-11-17 05:59:44 +00006137/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006138UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006139 UsingDecl *UD,
6140 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006141
6142 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006143 NamedDecl *Target = Orig;
6144 if (isa<UsingShadowDecl>(Target)) {
6145 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6146 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006147 }
6148
6149 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006150 = UsingShadowDecl::Create(Context, CurContext,
6151 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006152 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006153
6154 Shadow->setAccess(UD->getAccess());
6155 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6156 Shadow->setInvalidDecl();
6157
John McCall9488ea12009-11-17 05:59:44 +00006158 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006159 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006160 else
John McCall604e7f12009-12-08 07:46:18 +00006161 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006162
John McCall604e7f12009-12-08 07:46:18 +00006163
John McCall9f54ad42009-12-10 09:41:52 +00006164 return Shadow;
6165}
John McCall604e7f12009-12-08 07:46:18 +00006166
John McCall9f54ad42009-12-10 09:41:52 +00006167/// Hides a using shadow declaration. This is required by the current
6168/// using-decl implementation when a resolvable using declaration in a
6169/// class is followed by a declaration which would hide or override
6170/// one or more of the using decl's targets; for example:
6171///
6172/// struct Base { void foo(int); };
6173/// struct Derived : Base {
6174/// using Base::foo;
6175/// void foo(int);
6176/// };
6177///
6178/// The governing language is C++03 [namespace.udecl]p12:
6179///
6180/// When a using-declaration brings names from a base class into a
6181/// derived class scope, member functions in the derived class
6182/// override and/or hide member functions with the same name and
6183/// parameter types in a base class (rather than conflicting).
6184///
6185/// There are two ways to implement this:
6186/// (1) optimistically create shadow decls when they're not hidden
6187/// by existing declarations, or
6188/// (2) don't create any shadow decls (or at least don't make them
6189/// visible) until we've fully parsed/instantiated the class.
6190/// The problem with (1) is that we might have to retroactively remove
6191/// a shadow decl, which requires several O(n) operations because the
6192/// decl structures are (very reasonably) not designed for removal.
6193/// (2) avoids this but is very fiddly and phase-dependent.
6194void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006195 if (Shadow->getDeclName().getNameKind() ==
6196 DeclarationName::CXXConversionFunctionName)
6197 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6198
John McCall9f54ad42009-12-10 09:41:52 +00006199 // Remove it from the DeclContext...
6200 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006201
John McCall9f54ad42009-12-10 09:41:52 +00006202 // ...and the scope, if applicable...
6203 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006204 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006205 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006206 }
6207
John McCall9f54ad42009-12-10 09:41:52 +00006208 // ...and the using decl.
6209 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6210
6211 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006212 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006213}
6214
John McCall7ba107a2009-11-18 02:36:19 +00006215/// Builds a using declaration.
6216///
6217/// \param IsInstantiation - Whether this call arises from an
6218/// instantiation of an unresolved using declaration. We treat
6219/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006220NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6221 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006222 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006223 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006224 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006225 bool IsInstantiation,
6226 bool IsTypeName,
6227 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006228 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006229 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006230 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006231
Anders Carlsson550b14b2009-08-28 05:49:21 +00006232 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006233
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006234 if (SS.isEmpty()) {
6235 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006236 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006237 }
Mike Stump1eb44332009-09-09 15:08:12 +00006238
John McCall9f54ad42009-12-10 09:41:52 +00006239 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006240 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006241 ForRedeclaration);
6242 Previous.setHideTags(false);
6243 if (S) {
6244 LookupName(Previous, S);
6245
6246 // It is really dumb that we have to do this.
6247 LookupResult::Filter F = Previous.makeFilter();
6248 while (F.hasNext()) {
6249 NamedDecl *D = F.next();
6250 if (!isDeclInScope(D, CurContext, S))
6251 F.erase();
6252 }
6253 F.done();
6254 } else {
6255 assert(IsInstantiation && "no scope in non-instantiation");
6256 assert(CurContext->isRecord() && "scope not record in instantiation");
6257 LookupQualifiedName(Previous, CurContext);
6258 }
6259
John McCall9f54ad42009-12-10 09:41:52 +00006260 // Check for invalid redeclarations.
6261 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6262 return 0;
6263
6264 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006265 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6266 return 0;
6267
John McCallaf8e6ed2009-11-12 03:15:40 +00006268 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006269 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006270 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006271 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006272 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006273 // FIXME: not all declaration name kinds are legal here
6274 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6275 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006276 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006277 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006278 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006279 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6280 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006281 }
John McCalled976492009-12-04 22:46:56 +00006282 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006283 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6284 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006285 }
John McCalled976492009-12-04 22:46:56 +00006286 D->setAccess(AS);
6287 CurContext->addDecl(D);
6288
6289 if (!LookupContext) return D;
6290 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006291
John McCall77bb1aa2010-05-01 00:40:08 +00006292 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006293 UD->setInvalidDecl();
6294 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006295 }
6296
Sebastian Redlf677ea32011-02-05 19:23:19 +00006297 // Constructor inheriting using decls get special treatment.
6298 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006299 if (CheckInheritedConstructorUsingDecl(UD))
6300 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006301 return UD;
6302 }
6303
6304 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006305
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006306 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006307
John McCall604e7f12009-12-08 07:46:18 +00006308 // Unlike most lookups, we don't always want to hide tag
6309 // declarations: tag names are visible through the using declaration
6310 // even if hidden by ordinary names, *except* in a dependent context
6311 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006312 if (!IsInstantiation)
6313 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006314
John McCalla24dc2e2009-11-17 02:14:36 +00006315 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006316
John McCallf36e02d2009-10-09 21:13:30 +00006317 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006318 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006319 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006320 UD->setInvalidDecl();
6321 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006322 }
6323
John McCalled976492009-12-04 22:46:56 +00006324 if (R.isAmbiguous()) {
6325 UD->setInvalidDecl();
6326 return UD;
6327 }
Mike Stump1eb44332009-09-09 15:08:12 +00006328
John McCall7ba107a2009-11-18 02:36:19 +00006329 if (IsTypeName) {
6330 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006331 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006332 Diag(IdentLoc, diag::err_using_typename_non_type);
6333 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6334 Diag((*I)->getUnderlyingDecl()->getLocation(),
6335 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006336 UD->setInvalidDecl();
6337 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006338 }
6339 } else {
6340 // If we asked for a non-typename and we got a type, error out,
6341 // but only if this is an instantiation of an unresolved using
6342 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006343 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006344 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6345 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006346 UD->setInvalidDecl();
6347 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006348 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006349 }
6350
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006351 // C++0x N2914 [namespace.udecl]p6:
6352 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006353 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006354 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6355 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006356 UD->setInvalidDecl();
6357 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006358 }
Mike Stump1eb44332009-09-09 15:08:12 +00006359
John McCall9f54ad42009-12-10 09:41:52 +00006360 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6361 if (!CheckUsingShadowDecl(UD, *I, Previous))
6362 BuildUsingShadowDecl(S, UD, *I);
6363 }
John McCall9488ea12009-11-17 05:59:44 +00006364
6365 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006366}
6367
Sebastian Redlf677ea32011-02-05 19:23:19 +00006368/// Additional checks for a using declaration referring to a constructor name.
6369bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6370 if (UD->isTypeName()) {
6371 // FIXME: Cannot specify typename when specifying constructor
6372 return true;
6373 }
6374
Douglas Gregordc355712011-02-25 00:36:19 +00006375 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006376 assert(SourceType &&
6377 "Using decl naming constructor doesn't have type in scope spec.");
6378 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6379
6380 // Check whether the named type is a direct base class.
6381 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6382 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6383 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6384 BaseIt != BaseE; ++BaseIt) {
6385 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6386 if (CanonicalSourceType == BaseType)
6387 break;
6388 }
6389
6390 if (BaseIt == BaseE) {
6391 // Did not find SourceType in the bases.
6392 Diag(UD->getUsingLocation(),
6393 diag::err_using_decl_constructor_not_in_direct_base)
6394 << UD->getNameInfo().getSourceRange()
6395 << QualType(SourceType, 0) << TargetClass;
6396 return true;
6397 }
6398
6399 BaseIt->setInheritConstructors();
6400
6401 return false;
6402}
6403
John McCall9f54ad42009-12-10 09:41:52 +00006404/// Checks that the given using declaration is not an invalid
6405/// redeclaration. Note that this is checking only for the using decl
6406/// itself, not for any ill-formedness among the UsingShadowDecls.
6407bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6408 bool isTypeName,
6409 const CXXScopeSpec &SS,
6410 SourceLocation NameLoc,
6411 const LookupResult &Prev) {
6412 // C++03 [namespace.udecl]p8:
6413 // C++0x [namespace.udecl]p10:
6414 // A using-declaration is a declaration and can therefore be used
6415 // repeatedly where (and only where) multiple declarations are
6416 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006417 //
John McCall8a726212010-11-29 18:01:58 +00006418 // That's in non-member contexts.
6419 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006420 return false;
6421
6422 NestedNameSpecifier *Qual
6423 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6424
6425 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6426 NamedDecl *D = *I;
6427
6428 bool DTypename;
6429 NestedNameSpecifier *DQual;
6430 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6431 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006432 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006433 } else if (UnresolvedUsingValueDecl *UD
6434 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6435 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006436 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006437 } else if (UnresolvedUsingTypenameDecl *UD
6438 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6439 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006440 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006441 } else continue;
6442
6443 // using decls differ if one says 'typename' and the other doesn't.
6444 // FIXME: non-dependent using decls?
6445 if (isTypeName != DTypename) continue;
6446
6447 // using decls differ if they name different scopes (but note that
6448 // template instantiation can cause this check to trigger when it
6449 // didn't before instantiation).
6450 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6451 Context.getCanonicalNestedNameSpecifier(DQual))
6452 continue;
6453
6454 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006455 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006456 return true;
6457 }
6458
6459 return false;
6460}
6461
John McCall604e7f12009-12-08 07:46:18 +00006462
John McCalled976492009-12-04 22:46:56 +00006463/// Checks that the given nested-name qualifier used in a using decl
6464/// in the current context is appropriately related to the current
6465/// scope. If an error is found, diagnoses it and returns true.
6466bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6467 const CXXScopeSpec &SS,
6468 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006469 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006470
John McCall604e7f12009-12-08 07:46:18 +00006471 if (!CurContext->isRecord()) {
6472 // C++03 [namespace.udecl]p3:
6473 // C++0x [namespace.udecl]p8:
6474 // A using-declaration for a class member shall be a member-declaration.
6475
6476 // If we weren't able to compute a valid scope, it must be a
6477 // dependent class scope.
6478 if (!NamedContext || NamedContext->isRecord()) {
6479 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6480 << SS.getRange();
6481 return true;
6482 }
6483
6484 // Otherwise, everything is known to be fine.
6485 return false;
6486 }
6487
6488 // The current scope is a record.
6489
6490 // If the named context is dependent, we can't decide much.
6491 if (!NamedContext) {
6492 // FIXME: in C++0x, we can diagnose if we can prove that the
6493 // nested-name-specifier does not refer to a base class, which is
6494 // still possible in some cases.
6495
6496 // Otherwise we have to conservatively report that things might be
6497 // okay.
6498 return false;
6499 }
6500
6501 if (!NamedContext->isRecord()) {
6502 // Ideally this would point at the last name in the specifier,
6503 // but we don't have that level of source info.
6504 Diag(SS.getRange().getBegin(),
6505 diag::err_using_decl_nested_name_specifier_is_not_class)
6506 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6507 return true;
6508 }
6509
Douglas Gregor6fb07292010-12-21 07:41:49 +00006510 if (!NamedContext->isDependentContext() &&
6511 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6512 return true;
6513
John McCall604e7f12009-12-08 07:46:18 +00006514 if (getLangOptions().CPlusPlus0x) {
6515 // C++0x [namespace.udecl]p3:
6516 // In a using-declaration used as a member-declaration, the
6517 // nested-name-specifier shall name a base class of the class
6518 // being defined.
6519
6520 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6521 cast<CXXRecordDecl>(NamedContext))) {
6522 if (CurContext == NamedContext) {
6523 Diag(NameLoc,
6524 diag::err_using_decl_nested_name_specifier_is_current_class)
6525 << SS.getRange();
6526 return true;
6527 }
6528
6529 Diag(SS.getRange().getBegin(),
6530 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6531 << (NestedNameSpecifier*) SS.getScopeRep()
6532 << cast<CXXRecordDecl>(CurContext)
6533 << SS.getRange();
6534 return true;
6535 }
6536
6537 return false;
6538 }
6539
6540 // C++03 [namespace.udecl]p4:
6541 // A using-declaration used as a member-declaration shall refer
6542 // to a member of a base class of the class being defined [etc.].
6543
6544 // Salient point: SS doesn't have to name a base class as long as
6545 // lookup only finds members from base classes. Therefore we can
6546 // diagnose here only if we can prove that that can't happen,
6547 // i.e. if the class hierarchies provably don't intersect.
6548
6549 // TODO: it would be nice if "definitely valid" results were cached
6550 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6551 // need to be repeated.
6552
6553 struct UserData {
6554 llvm::DenseSet<const CXXRecordDecl*> Bases;
6555
6556 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6557 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6558 Data->Bases.insert(Base);
6559 return true;
6560 }
6561
6562 bool hasDependentBases(const CXXRecordDecl *Class) {
6563 return !Class->forallBases(collect, this);
6564 }
6565
6566 /// Returns true if the base is dependent or is one of the
6567 /// accumulated base classes.
6568 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6569 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6570 return !Data->Bases.count(Base);
6571 }
6572
6573 bool mightShareBases(const CXXRecordDecl *Class) {
6574 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6575 }
6576 };
6577
6578 UserData Data;
6579
6580 // Returns false if we find a dependent base.
6581 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6582 return false;
6583
6584 // Returns false if the class has a dependent base or if it or one
6585 // of its bases is present in the base set of the current context.
6586 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6587 return false;
6588
6589 Diag(SS.getRange().getBegin(),
6590 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6591 << (NestedNameSpecifier*) SS.getScopeRep()
6592 << cast<CXXRecordDecl>(CurContext)
6593 << SS.getRange();
6594
6595 return true;
John McCalled976492009-12-04 22:46:56 +00006596}
6597
Richard Smith162e1c12011-04-15 14:24:37 +00006598Decl *Sema::ActOnAliasDeclaration(Scope *S,
6599 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006600 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006601 SourceLocation UsingLoc,
6602 UnqualifiedId &Name,
6603 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006604 // Skip up to the relevant declaration scope.
6605 while (S->getFlags() & Scope::TemplateParamScope)
6606 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006607 assert((S->getFlags() & Scope::DeclScope) &&
6608 "got alias-declaration outside of declaration scope");
6609
6610 if (Type.isInvalid())
6611 return 0;
6612
6613 bool Invalid = false;
6614 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6615 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006616 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006617
6618 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6619 return 0;
6620
6621 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006622 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006623 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006624 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6625 TInfo->getTypeLoc().getBeginLoc());
6626 }
Richard Smith162e1c12011-04-15 14:24:37 +00006627
6628 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6629 LookupName(Previous, S);
6630
6631 // Warn about shadowing the name of a template parameter.
6632 if (Previous.isSingleResult() &&
6633 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006634 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006635 Previous.clear();
6636 }
6637
6638 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6639 "name in alias declaration must be an identifier");
6640 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6641 Name.StartLocation,
6642 Name.Identifier, TInfo);
6643
6644 NewTD->setAccess(AS);
6645
6646 if (Invalid)
6647 NewTD->setInvalidDecl();
6648
Richard Smith3e4c6c42011-05-05 21:57:07 +00006649 CheckTypedefForVariablyModifiedType(S, NewTD);
6650 Invalid |= NewTD->isInvalidDecl();
6651
Richard Smith162e1c12011-04-15 14:24:37 +00006652 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006653
6654 NamedDecl *NewND;
6655 if (TemplateParamLists.size()) {
6656 TypeAliasTemplateDecl *OldDecl = 0;
6657 TemplateParameterList *OldTemplateParams = 0;
6658
6659 if (TemplateParamLists.size() != 1) {
6660 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6661 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6662 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6663 }
6664 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6665
6666 // Only consider previous declarations in the same scope.
6667 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6668 /*ExplicitInstantiationOrSpecialization*/false);
6669 if (!Previous.empty()) {
6670 Redeclaration = true;
6671
6672 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6673 if (!OldDecl && !Invalid) {
6674 Diag(UsingLoc, diag::err_redefinition_different_kind)
6675 << Name.Identifier;
6676
6677 NamedDecl *OldD = Previous.getRepresentativeDecl();
6678 if (OldD->getLocation().isValid())
6679 Diag(OldD->getLocation(), diag::note_previous_definition);
6680
6681 Invalid = true;
6682 }
6683
6684 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6685 if (TemplateParameterListsAreEqual(TemplateParams,
6686 OldDecl->getTemplateParameters(),
6687 /*Complain=*/true,
6688 TPL_TemplateMatch))
6689 OldTemplateParams = OldDecl->getTemplateParameters();
6690 else
6691 Invalid = true;
6692
6693 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6694 if (!Invalid &&
6695 !Context.hasSameType(OldTD->getUnderlyingType(),
6696 NewTD->getUnderlyingType())) {
6697 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6698 // but we can't reasonably accept it.
6699 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6700 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6701 if (OldTD->getLocation().isValid())
6702 Diag(OldTD->getLocation(), diag::note_previous_definition);
6703 Invalid = true;
6704 }
6705 }
6706 }
6707
6708 // Merge any previous default template arguments into our parameters,
6709 // and check the parameter list.
6710 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6711 TPC_TypeAliasTemplate))
6712 return 0;
6713
6714 TypeAliasTemplateDecl *NewDecl =
6715 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6716 Name.Identifier, TemplateParams,
6717 NewTD);
6718
6719 NewDecl->setAccess(AS);
6720
6721 if (Invalid)
6722 NewDecl->setInvalidDecl();
6723 else if (OldDecl)
6724 NewDecl->setPreviousDeclaration(OldDecl);
6725
6726 NewND = NewDecl;
6727 } else {
6728 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6729 NewND = NewTD;
6730 }
Richard Smith162e1c12011-04-15 14:24:37 +00006731
6732 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006733 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006734
Richard Smith3e4c6c42011-05-05 21:57:07 +00006735 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006736}
6737
John McCalld226f652010-08-21 09:40:31 +00006738Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006739 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006740 SourceLocation AliasLoc,
6741 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006742 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006743 SourceLocation IdentLoc,
6744 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006745
Anders Carlsson81c85c42009-03-28 23:53:49 +00006746 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006747 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6748 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006749
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006750 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006751 NamedDecl *PrevDecl
6752 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6753 ForRedeclaration);
6754 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6755 PrevDecl = 0;
6756
6757 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006758 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006759 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006760 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006761 // FIXME: At some point, we'll want to create the (redundant)
6762 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006763 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006764 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006765 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006766 }
Mike Stump1eb44332009-09-09 15:08:12 +00006767
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006768 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6769 diag::err_redefinition_different_kind;
6770 Diag(AliasLoc, DiagID) << Alias;
6771 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006772 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006773 }
6774
John McCalla24dc2e2009-11-17 02:14:36 +00006775 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006776 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006777
John McCallf36e02d2009-10-09 21:13:30 +00006778 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006779 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006780 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006781 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006782 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006783 }
Mike Stump1eb44332009-09-09 15:08:12 +00006784
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006785 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006786 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006787 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006788 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006789
John McCall3dbd3d52010-02-16 06:53:13 +00006790 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006791 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006792}
6793
Douglas Gregor39957dc2010-05-01 15:04:51 +00006794namespace {
6795 /// \brief Scoped object used to handle the state changes required in Sema
6796 /// to implicitly define the body of a C++ member function;
6797 class ImplicitlyDefinedFunctionScope {
6798 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006799 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006800
6801 public:
6802 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006803 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006804 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006805 S.PushFunctionScope();
6806 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6807 }
6808
6809 ~ImplicitlyDefinedFunctionScope() {
6810 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006811 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006812 }
6813 };
6814}
6815
Sean Hunt001cad92011-05-10 00:49:42 +00006816Sema::ImplicitExceptionSpecification
6817Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006818 // C++ [except.spec]p14:
6819 // An implicitly declared special member function (Clause 12) shall have an
6820 // exception-specification. [...]
6821 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006822 if (ClassDecl->isInvalidDecl())
6823 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006824
Sebastian Redl60618fa2011-03-12 11:50:43 +00006825 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006826 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6827 BEnd = ClassDecl->bases_end();
6828 B != BEnd; ++B) {
6829 if (B->isVirtual()) // Handled below.
6830 continue;
6831
Douglas Gregor18274032010-07-03 00:47:00 +00006832 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6833 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006834 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6835 // If this is a deleted function, add it anyway. This might be conformant
6836 // with the standard. This might not. I'm not sure. It might not matter.
6837 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006838 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006839 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006840 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006841
6842 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006843 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6844 BEnd = ClassDecl->vbases_end();
6845 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006846 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6847 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006848 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6849 // If this is a deleted function, add it anyway. This might be conformant
6850 // with the standard. This might not. I'm not sure. It might not matter.
6851 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006852 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006853 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006854 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006855
6856 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006857 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6858 FEnd = ClassDecl->field_end();
6859 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006860 if (F->hasInClassInitializer()) {
6861 if (Expr *E = F->getInClassInitializer())
6862 ExceptSpec.CalledExpr(E);
6863 else if (!F->isInvalidDecl())
6864 ExceptSpec.SetDelayed();
6865 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006866 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006867 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6868 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6869 // If this is a deleted function, add it anyway. This might be conformant
6870 // with the standard. This might not. I'm not sure. It might not matter.
6871 // In particular, the problem is that this function never gets called. It
6872 // might just be ill-formed because this function attempts to refer to
6873 // a deleted function here.
6874 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006875 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006876 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006877 }
John McCalle23cf432010-12-14 08:05:40 +00006878
Sean Hunt001cad92011-05-10 00:49:42 +00006879 return ExceptSpec;
6880}
6881
6882CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6883 CXXRecordDecl *ClassDecl) {
6884 // C++ [class.ctor]p5:
6885 // A default constructor for a class X is a constructor of class X
6886 // that can be called without an argument. If there is no
6887 // user-declared constructor for class X, a default constructor is
6888 // implicitly declared. An implicitly-declared default constructor
6889 // is an inline public member of its class.
6890 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6891 "Should not build implicit default constructor!");
6892
6893 ImplicitExceptionSpecification Spec =
6894 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6895 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006896
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006897 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006898 CanQualType ClassType
6899 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006900 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006901 DeclarationName Name
6902 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006903 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006904 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6905 Context, ClassDecl, ClassLoc, NameInfo,
6906 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6907 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6908 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
6909 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006910 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006911 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006912 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006913 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006914
6915 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006916 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6917
Douglas Gregor23c94db2010-07-02 17:43:08 +00006918 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006919 PushOnScopeChains(DefaultCon, S, false);
6920 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006921
Sean Hunte16da072011-10-10 06:18:57 +00006922 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006923 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006924
Douglas Gregor32df23e2010-07-01 22:02:46 +00006925 return DefaultCon;
6926}
6927
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006928void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6929 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006930 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006931 !Constructor->doesThisDeclarationHaveABody() &&
6932 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006933 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006934
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006935 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006936 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006937
Douglas Gregor39957dc2010-05-01 15:04:51 +00006938 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006939 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006940 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006941 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006942 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006943 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006944 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006945 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006946 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006947
6948 SourceLocation Loc = Constructor->getLocation();
6949 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6950
6951 Constructor->setUsed();
6952 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006953
6954 if (ASTMutationListener *L = getASTMutationListener()) {
6955 L->CompletedImplicitDefinition(Constructor);
6956 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006957}
6958
Richard Smith7a614d82011-06-11 17:19:42 +00006959/// Get any existing defaulted default constructor for the given class. Do not
6960/// implicitly define one if it does not exist.
6961static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6962 CXXRecordDecl *D) {
6963 ASTContext &Context = Self.Context;
6964 QualType ClassType = Context.getTypeDeclType(D);
6965 DeclarationName ConstructorName
6966 = Context.DeclarationNames.getCXXConstructorName(
6967 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6968
6969 DeclContext::lookup_const_iterator Con, ConEnd;
6970 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6971 Con != ConEnd; ++Con) {
6972 // A function template cannot be defaulted.
6973 if (isa<FunctionTemplateDecl>(*Con))
6974 continue;
6975
6976 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6977 if (Constructor->isDefaultConstructor())
6978 return Constructor->isDefaulted() ? Constructor : 0;
6979 }
6980 return 0;
6981}
6982
6983void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6984 if (!D) return;
6985 AdjustDeclIfTemplate(D);
6986
6987 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6988 CXXConstructorDecl *CtorDecl
6989 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6990
6991 if (!CtorDecl) return;
6992
6993 // Compute the exception specification for the default constructor.
6994 const FunctionProtoType *CtorTy =
6995 CtorDecl->getType()->castAs<FunctionProtoType>();
6996 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6997 ImplicitExceptionSpecification Spec =
6998 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6999 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7000 assert(EPI.ExceptionSpecType != EST_Delayed);
7001
7002 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7003 }
7004
7005 // If the default constructor is explicitly defaulted, checking the exception
7006 // specification is deferred until now.
7007 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7008 !ClassDecl->isDependentType())
7009 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7010}
7011
Sebastian Redlf677ea32011-02-05 19:23:19 +00007012void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7013 // We start with an initial pass over the base classes to collect those that
7014 // inherit constructors from. If there are none, we can forgo all further
7015 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007016 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007017 BasesVector BasesToInheritFrom;
7018 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7019 BaseE = ClassDecl->bases_end();
7020 BaseIt != BaseE; ++BaseIt) {
7021 if (BaseIt->getInheritConstructors()) {
7022 QualType Base = BaseIt->getType();
7023 if (Base->isDependentType()) {
7024 // If we inherit constructors from anything that is dependent, just
7025 // abort processing altogether. We'll get another chance for the
7026 // instantiations.
7027 return;
7028 }
7029 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7030 }
7031 }
7032 if (BasesToInheritFrom.empty())
7033 return;
7034
7035 // Now collect the constructors that we already have in the current class.
7036 // Those take precedence over inherited constructors.
7037 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7038 // unless there is a user-declared constructor with the same signature in
7039 // the class where the using-declaration appears.
7040 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7041 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7042 CtorE = ClassDecl->ctor_end();
7043 CtorIt != CtorE; ++CtorIt) {
7044 ExistingConstructors.insert(
7045 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7046 }
7047
7048 Scope *S = getScopeForContext(ClassDecl);
7049 DeclarationName CreatedCtorName =
7050 Context.DeclarationNames.getCXXConstructorName(
7051 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7052
7053 // Now comes the true work.
7054 // First, we keep a map from constructor types to the base that introduced
7055 // them. Needed for finding conflicting constructors. We also keep the
7056 // actually inserted declarations in there, for pretty diagnostics.
7057 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7058 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7059 ConstructorToSourceMap InheritedConstructors;
7060 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7061 BaseE = BasesToInheritFrom.end();
7062 BaseIt != BaseE; ++BaseIt) {
7063 const RecordType *Base = *BaseIt;
7064 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7065 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7066 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7067 CtorE = BaseDecl->ctor_end();
7068 CtorIt != CtorE; ++CtorIt) {
7069 // Find the using declaration for inheriting this base's constructors.
7070 DeclarationName Name =
7071 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7072 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7073 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7074 SourceLocation UsingLoc = UD ? UD->getLocation() :
7075 ClassDecl->getLocation();
7076
7077 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7078 // from the class X named in the using-declaration consists of actual
7079 // constructors and notional constructors that result from the
7080 // transformation of defaulted parameters as follows:
7081 // - all non-template default constructors of X, and
7082 // - for each non-template constructor of X that has at least one
7083 // parameter with a default argument, the set of constructors that
7084 // results from omitting any ellipsis parameter specification and
7085 // successively omitting parameters with a default argument from the
7086 // end of the parameter-type-list.
7087 CXXConstructorDecl *BaseCtor = *CtorIt;
7088 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7089 const FunctionProtoType *BaseCtorType =
7090 BaseCtor->getType()->getAs<FunctionProtoType>();
7091
7092 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7093 maxParams = BaseCtor->getNumParams();
7094 params <= maxParams; ++params) {
7095 // Skip default constructors. They're never inherited.
7096 if (params == 0)
7097 continue;
7098 // Skip copy and move constructors for the same reason.
7099 if (CanBeCopyOrMove && params == 1)
7100 continue;
7101
7102 // Build up a function type for this particular constructor.
7103 // FIXME: The working paper does not consider that the exception spec
7104 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007105 // source. This code doesn't yet, either. When it does, this code will
7106 // need to be delayed until after exception specifications and in-class
7107 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007108 const Type *NewCtorType;
7109 if (params == maxParams)
7110 NewCtorType = BaseCtorType;
7111 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007112 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007113 for (unsigned i = 0; i < params; ++i) {
7114 Args.push_back(BaseCtorType->getArgType(i));
7115 }
7116 FunctionProtoType::ExtProtoInfo ExtInfo =
7117 BaseCtorType->getExtProtoInfo();
7118 ExtInfo.Variadic = false;
7119 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7120 Args.data(), params, ExtInfo)
7121 .getTypePtr();
7122 }
7123 const Type *CanonicalNewCtorType =
7124 Context.getCanonicalType(NewCtorType);
7125
7126 // Now that we have the type, first check if the class already has a
7127 // constructor with this signature.
7128 if (ExistingConstructors.count(CanonicalNewCtorType))
7129 continue;
7130
7131 // Then we check if we have already declared an inherited constructor
7132 // with this signature.
7133 std::pair<ConstructorToSourceMap::iterator, bool> result =
7134 InheritedConstructors.insert(std::make_pair(
7135 CanonicalNewCtorType,
7136 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7137 if (!result.second) {
7138 // Already in the map. If it came from a different class, that's an
7139 // error. Not if it's from the same.
7140 CanQualType PreviousBase = result.first->second.first;
7141 if (CanonicalBase != PreviousBase) {
7142 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7143 const CXXConstructorDecl *PrevBaseCtor =
7144 PrevCtor->getInheritedConstructor();
7145 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7146
7147 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7148 Diag(BaseCtor->getLocation(),
7149 diag::note_using_decl_constructor_conflict_current_ctor);
7150 Diag(PrevBaseCtor->getLocation(),
7151 diag::note_using_decl_constructor_conflict_previous_ctor);
7152 Diag(PrevCtor->getLocation(),
7153 diag::note_using_decl_constructor_conflict_previous_using);
7154 }
7155 continue;
7156 }
7157
7158 // OK, we're there, now add the constructor.
7159 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007160 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007161 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7162 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007163 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7164 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007165 /*ImplicitlyDeclared=*/true,
7166 // FIXME: Due to a defect in the standard, we treat inherited
7167 // constructors as constexpr even if that makes them ill-formed.
7168 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007169 NewCtor->setAccess(BaseCtor->getAccess());
7170
7171 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007172 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007173 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007174 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7175 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007176 /*IdentifierInfo=*/0,
7177 BaseCtorType->getArgType(i),
7178 /*TInfo=*/0, SC_None,
7179 SC_None, /*DefaultArg=*/0));
7180 }
David Blaikie4278c652011-09-21 18:16:56 +00007181 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007182 NewCtor->setInheritedConstructor(BaseCtor);
7183
7184 PushOnScopeChains(NewCtor, S, false);
7185 ClassDecl->addDecl(NewCtor);
7186 result.first->second.second = NewCtor;
7187 }
7188 }
7189 }
7190}
7191
Sean Huntcb45a0f2011-05-12 22:46:25 +00007192Sema::ImplicitExceptionSpecification
7193Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007194 // C++ [except.spec]p14:
7195 // An implicitly declared special member function (Clause 12) shall have
7196 // an exception-specification.
7197 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007198 if (ClassDecl->isInvalidDecl())
7199 return ExceptSpec;
7200
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007201 // Direct base-class destructors.
7202 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7203 BEnd = ClassDecl->bases_end();
7204 B != BEnd; ++B) {
7205 if (B->isVirtual()) // Handled below.
7206 continue;
7207
7208 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7209 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007210 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007211 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007212
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007213 // Virtual base-class destructors.
7214 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7215 BEnd = ClassDecl->vbases_end();
7216 B != BEnd; ++B) {
7217 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7218 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007219 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007220 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007221
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007222 // Field destructors.
7223 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7224 FEnd = ClassDecl->field_end();
7225 F != FEnd; ++F) {
7226 if (const RecordType *RecordTy
7227 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7228 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007229 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007230 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007231
Sean Huntcb45a0f2011-05-12 22:46:25 +00007232 return ExceptSpec;
7233}
7234
7235CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7236 // C++ [class.dtor]p2:
7237 // If a class has no user-declared destructor, a destructor is
7238 // declared implicitly. An implicitly-declared destructor is an
7239 // inline public member of its class.
7240
7241 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007242 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007243 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7244
Douglas Gregor4923aa22010-07-02 20:37:36 +00007245 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007246 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007247
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007248 CanQualType ClassType
7249 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007250 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007251 DeclarationName Name
7252 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007253 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007254 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007255 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7256 /*isInline=*/true,
7257 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007258 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007259 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007260 Destructor->setImplicit();
7261 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007262
7263 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007264 ++ASTContext::NumImplicitDestructorsDeclared;
7265
7266 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007267 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007268 PushOnScopeChains(Destructor, S, false);
7269 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007270
7271 // This could be uniqued if it ever proves significant.
7272 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007273
7274 if (ShouldDeleteDestructor(Destructor))
7275 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007276
7277 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007278
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007279 return Destructor;
7280}
7281
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007282void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007283 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007284 assert((Destructor->isDefaulted() &&
7285 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007286 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007287 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007288 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007289
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007290 if (Destructor->isInvalidDecl())
7291 return;
7292
Douglas Gregor39957dc2010-05-01 15:04:51 +00007293 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007294
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007295 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007296 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7297 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007298
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007299 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007300 Diag(CurrentLocation, diag::note_member_synthesized_at)
7301 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7302
7303 Destructor->setInvalidDecl();
7304 return;
7305 }
7306
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007307 SourceLocation Loc = Destructor->getLocation();
7308 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007309 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007310 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007311 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007312
7313 if (ASTMutationListener *L = getASTMutationListener()) {
7314 L->CompletedImplicitDefinition(Destructor);
7315 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007316}
7317
Sebastian Redl0ee33912011-05-19 05:13:44 +00007318void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7319 CXXDestructorDecl *destructor) {
7320 // C++11 [class.dtor]p3:
7321 // A declaration of a destructor that does not have an exception-
7322 // specification is implicitly considered to have the same exception-
7323 // specification as an implicit declaration.
7324 const FunctionProtoType *dtorType = destructor->getType()->
7325 getAs<FunctionProtoType>();
7326 if (dtorType->hasExceptionSpec())
7327 return;
7328
7329 ImplicitExceptionSpecification exceptSpec =
7330 ComputeDefaultedDtorExceptionSpec(classDecl);
7331
Chandler Carruth3f224b22011-09-20 04:55:26 +00007332 // Replace the destructor's type, building off the existing one. Fortunately,
7333 // the only thing of interest in the destructor type is its extended info.
7334 // The return and arguments are fixed.
7335 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007336 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7337 epi.NumExceptions = exceptSpec.size();
7338 epi.Exceptions = exceptSpec.data();
7339 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7340
7341 destructor->setType(ty);
7342
7343 // FIXME: If the destructor has a body that could throw, and the newly created
7344 // spec doesn't allow exceptions, we should emit a warning, because this
7345 // change in behavior can break conforming C++03 programs at runtime.
7346 // However, we don't have a body yet, so it needs to be done somewhere else.
7347}
7348
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007349/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007350/// \c To.
7351///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007352/// This routine is used to copy/move the members of a class with an
7353/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007354/// copied are arrays, this routine builds for loops to copy them.
7355///
7356/// \param S The Sema object used for type-checking.
7357///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007358/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007359///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007360/// \param T The type of the expressions being copied/moved. Both expressions
7361/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007362///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007363/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007364///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007365/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007366///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007367/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007368/// Otherwise, it's a non-static member subobject.
7369///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007370/// \param Copying Whether we're copying or moving.
7371///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007372/// \param Depth Internal parameter recording the depth of the recursion.
7373///
7374/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007375static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007376BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007377 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007378 bool CopyingBaseSubobject, bool Copying,
7379 unsigned Depth = 0) {
7380 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007381 // Each subobject is assigned in the manner appropriate to its type:
7382 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007383 // - if the subobject is of class type, as if by a call to operator= with
7384 // the subobject as the object expression and the corresponding
7385 // subobject of x as a single function argument (as if by explicit
7386 // qualification; that is, ignoring any possible virtual overriding
7387 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007388 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7389 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7390
7391 // Look for operator=.
7392 DeclarationName Name
7393 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7394 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7395 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7396
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007397 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007398 LookupResult::Filter F = OpLookup.makeFilter();
7399 while (F.hasNext()) {
7400 NamedDecl *D = F.next();
7401 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007402 if (Copying ? Method->isCopyAssignmentOperator() :
7403 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007404 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007405
Douglas Gregor06a9f362010-05-01 20:49:11 +00007406 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007407 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007408 F.done();
7409
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007410 // Suppress the protected check (C++ [class.protected]) for each of the
7411 // assignment operators we found. This strange dance is required when
7412 // we're assigning via a base classes's copy-assignment operator. To
7413 // ensure that we're getting the right base class subobject (without
7414 // ambiguities), we need to cast "this" to that subobject type; to
7415 // ensure that we don't go through the virtual call mechanism, we need
7416 // to qualify the operator= name with the base class (see below). However,
7417 // this means that if the base class has a protected copy assignment
7418 // operator, the protected member access check will fail. So, we
7419 // rewrite "protected" access to "public" access in this case, since we
7420 // know by construction that we're calling from a derived class.
7421 if (CopyingBaseSubobject) {
7422 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7423 L != LEnd; ++L) {
7424 if (L.getAccess() == AS_protected)
7425 L.setAccess(AS_public);
7426 }
7427 }
7428
Douglas Gregor06a9f362010-05-01 20:49:11 +00007429 // Create the nested-name-specifier that will be used to qualify the
7430 // reference to operator=; this is required to suppress the virtual
7431 // call mechanism.
7432 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007433 SS.MakeTrivial(S.Context,
7434 NestedNameSpecifier::Create(S.Context, 0, false,
7435 T.getTypePtr()),
7436 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007437
7438 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007439 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007440 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007441 /*FirstQualifierInScope=*/0, OpLookup,
7442 /*TemplateArgs=*/0,
7443 /*SuppressQualifierCheck=*/true);
7444 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007445 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007446
7447 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007448
John McCall60d7b3a2010-08-24 06:29:42 +00007449 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007450 OpEqualRef.takeAs<Expr>(),
7451 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007452 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007453 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007454
7455 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007456 }
John McCallb0207482010-03-16 06:11:48 +00007457
Douglas Gregor06a9f362010-05-01 20:49:11 +00007458 // - if the subobject is of scalar type, the built-in assignment
7459 // operator is used.
7460 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7461 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007462 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007463 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007464 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007465
7466 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007467 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007468
7469 // - if the subobject is an array, each element is assigned, in the
7470 // manner appropriate to the element type;
7471
7472 // Construct a loop over the array bounds, e.g.,
7473 //
7474 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7475 //
7476 // that will copy each of the array elements.
7477 QualType SizeType = S.Context.getSizeType();
7478
7479 // Create the iteration variable.
7480 IdentifierInfo *IterationVarName = 0;
7481 {
7482 llvm::SmallString<8> Str;
7483 llvm::raw_svector_ostream OS(Str);
7484 OS << "__i" << Depth;
7485 IterationVarName = &S.Context.Idents.get(OS.str());
7486 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007487 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007488 IterationVarName, SizeType,
7489 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007490 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007491
7492 // Initialize the iteration variable to zero.
7493 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007494 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007495
7496 // Create a reference to the iteration variable; we'll use this several
7497 // times throughout.
7498 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007499 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007500 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7501
7502 // Create the DeclStmt that holds the iteration variable.
7503 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7504
7505 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007506 llvm::APInt Upper
7507 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007508 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007509 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007510 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7511 BO_NE, S.Context.BoolTy,
7512 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007513
7514 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007515 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007516 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7517 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007518
7519 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007520 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7521 IterationVarRef, Loc));
7522 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7523 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007524 if (!Copying) // Cast to rvalue
7525 From = CastForMoving(S, From);
7526
7527 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007528 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7529 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007530 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007531 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007532 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007533
7534 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007535 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007536 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007537 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007538 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007539}
7540
Sean Hunt30de05c2011-05-14 05:23:20 +00007541std::pair<Sema::ImplicitExceptionSpecification, bool>
7542Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7543 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007544 if (ClassDecl->isInvalidDecl())
7545 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7546
Douglas Gregord3c35902010-07-01 16:36:15 +00007547 // C++ [class.copy]p10:
7548 // If the class definition does not explicitly declare a copy
7549 // assignment operator, one is declared implicitly.
7550 // The implicitly-defined copy assignment operator for a class X
7551 // will have the form
7552 //
7553 // X& X::operator=(const X&)
7554 //
7555 // if
7556 bool HasConstCopyAssignment = true;
7557
7558 // -- each direct base class B of X has a copy assignment operator
7559 // whose parameter is of type const B&, const volatile B& or B,
7560 // and
7561 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7562 BaseEnd = ClassDecl->bases_end();
7563 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007564 // We'll handle this below
7565 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7566 continue;
7567
Douglas Gregord3c35902010-07-01 16:36:15 +00007568 assert(!Base->getType()->isDependentType() &&
7569 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007570 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7571 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7572 &HasConstCopyAssignment);
7573 }
7574
Richard Smithebaf0e62011-10-18 20:49:44 +00007575 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007576 if (LangOpts.CPlusPlus0x) {
7577 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7578 BaseEnd = ClassDecl->vbases_end();
7579 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7580 assert(!Base->getType()->isDependentType() &&
7581 "Cannot generate implicit members for class with dependent bases.");
7582 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7583 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7584 &HasConstCopyAssignment);
7585 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007586 }
7587
7588 // -- for all the nonstatic data members of X that are of a class
7589 // type M (or array thereof), each such class type has a copy
7590 // assignment operator whose parameter is of type const M&,
7591 // const volatile M& or M.
7592 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7593 FieldEnd = ClassDecl->field_end();
7594 HasConstCopyAssignment && Field != FieldEnd;
7595 ++Field) {
7596 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007597 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7598 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7599 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007600 }
7601 }
7602
7603 // Otherwise, the implicitly declared copy assignment operator will
7604 // have the form
7605 //
7606 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007607
Douglas Gregorb87786f2010-07-01 17:48:08 +00007608 // C++ [except.spec]p14:
7609 // An implicitly declared special member function (Clause 12) shall have an
7610 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007611
7612 // It is unspecified whether or not an implicit copy assignment operator
7613 // attempts to deduplicate calls to assignment operators of virtual bases are
7614 // made. As such, this exception specification is effectively unspecified.
7615 // Based on a similar decision made for constness in C++0x, we're erring on
7616 // the side of assuming such calls to be made regardless of whether they
7617 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007618 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007619 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007620 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7621 BaseEnd = ClassDecl->bases_end();
7622 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007623 if (Base->isVirtual())
7624 continue;
7625
Douglas Gregora376d102010-07-02 21:50:04 +00007626 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007627 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007628 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7629 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007630 ExceptSpec.CalledDecl(CopyAssign);
7631 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007632
7633 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7634 BaseEnd = ClassDecl->vbases_end();
7635 Base != BaseEnd; ++Base) {
7636 CXXRecordDecl *BaseClassDecl
7637 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7638 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7639 ArgQuals, false, 0))
7640 ExceptSpec.CalledDecl(CopyAssign);
7641 }
7642
Douglas Gregorb87786f2010-07-01 17:48:08 +00007643 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7644 FieldEnd = ClassDecl->field_end();
7645 Field != FieldEnd;
7646 ++Field) {
7647 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007648 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7649 if (CXXMethodDecl *CopyAssign =
7650 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7651 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007652 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007653 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007654
Sean Hunt30de05c2011-05-14 05:23:20 +00007655 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7656}
7657
7658CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7659 // Note: The following rules are largely analoguous to the copy
7660 // constructor rules. Note that virtual bases are not taken into account
7661 // for determining the argument type of the operator. Note also that
7662 // operators taking an object instead of a reference are allowed.
7663
7664 ImplicitExceptionSpecification Spec(Context);
7665 bool Const;
7666 llvm::tie(Spec, Const) =
7667 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7668
7669 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7670 QualType RetType = Context.getLValueReferenceType(ArgType);
7671 if (Const)
7672 ArgType = ArgType.withConst();
7673 ArgType = Context.getLValueReferenceType(ArgType);
7674
Douglas Gregord3c35902010-07-01 16:36:15 +00007675 // An implicitly-declared copy assignment operator is an inline public
7676 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007677 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007678 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007679 SourceLocation ClassLoc = ClassDecl->getLocation();
7680 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007681 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007682 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007683 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007684 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007685 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007686 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007687 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007688 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007689 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007690 CopyAssignment->setImplicit();
7691 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007692
7693 // Add the parameter to the operator.
7694 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007695 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007696 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007697 SC_None,
7698 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007699 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007700
Douglas Gregora376d102010-07-02 21:50:04 +00007701 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007702 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007703
Douglas Gregor23c94db2010-07-02 17:43:08 +00007704 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007705 PushOnScopeChains(CopyAssignment, S, false);
7706 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007707
Sean Hunt1ccbc542011-06-22 01:05:13 +00007708 // C++0x [class.copy]p18:
7709 // ... If the class definition declares a move constructor or move
7710 // assignment operator, the implicitly declared copy assignment operator is
7711 // defined as deleted; ...
7712 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7713 ClassDecl->hasUserDeclaredMoveAssignment() ||
7714 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007715 CopyAssignment->setDeletedAsWritten();
7716
Douglas Gregord3c35902010-07-01 16:36:15 +00007717 AddOverriddenMethods(ClassDecl, CopyAssignment);
7718 return CopyAssignment;
7719}
7720
Douglas Gregor06a9f362010-05-01 20:49:11 +00007721void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7722 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007723 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007724 CopyAssignOperator->isOverloadedOperator() &&
7725 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007726 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007727 "DefineImplicitCopyAssignment called for wrong function");
7728
7729 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7730
7731 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7732 CopyAssignOperator->setInvalidDecl();
7733 return;
7734 }
7735
7736 CopyAssignOperator->setUsed();
7737
7738 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007739 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007740
7741 // C++0x [class.copy]p30:
7742 // The implicitly-defined or explicitly-defaulted copy assignment operator
7743 // for a non-union class X performs memberwise copy assignment of its
7744 // subobjects. The direct base classes of X are assigned first, in the
7745 // order of their declaration in the base-specifier-list, and then the
7746 // immediate non-static data members of X are assigned, in the order in
7747 // which they were declared in the class definition.
7748
7749 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007750 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007751
7752 // The parameter for the "other" object, which we are copying from.
7753 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7754 Qualifiers OtherQuals = Other->getType().getQualifiers();
7755 QualType OtherRefType = Other->getType();
7756 if (const LValueReferenceType *OtherRef
7757 = OtherRefType->getAs<LValueReferenceType>()) {
7758 OtherRefType = OtherRef->getPointeeType();
7759 OtherQuals = OtherRefType.getQualifiers();
7760 }
7761
7762 // Our location for everything implicitly-generated.
7763 SourceLocation Loc = CopyAssignOperator->getLocation();
7764
7765 // Construct a reference to the "other" object. We'll be using this
7766 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007767 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007768 assert(OtherRef && "Reference to parameter cannot fail!");
7769
7770 // Construct the "this" pointer. We'll be using this throughout the generated
7771 // ASTs.
7772 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7773 assert(This && "Reference to this cannot fail!");
7774
7775 // Assign base classes.
7776 bool Invalid = false;
7777 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7778 E = ClassDecl->bases_end(); Base != E; ++Base) {
7779 // Form the assignment:
7780 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7781 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007782 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007783 Invalid = true;
7784 continue;
7785 }
7786
John McCallf871d0c2010-08-07 06:22:56 +00007787 CXXCastPath BasePath;
7788 BasePath.push_back(Base);
7789
Douglas Gregor06a9f362010-05-01 20:49:11 +00007790 // Construct the "from" expression, which is an implicit cast to the
7791 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007792 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007793 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7794 CK_UncheckedDerivedToBase,
7795 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007796
7797 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007798 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007799
7800 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007801 To = ImpCastExprToType(To.take(),
7802 Context.getCVRQualifiedType(BaseType,
7803 CopyAssignOperator->getTypeQualifiers()),
7804 CK_UncheckedDerivedToBase,
7805 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007806
7807 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007808 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007809 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007810 /*CopyingBaseSubobject=*/true,
7811 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007812 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007813 Diag(CurrentLocation, diag::note_member_synthesized_at)
7814 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7815 CopyAssignOperator->setInvalidDecl();
7816 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007817 }
7818
7819 // Success! Record the copy.
7820 Statements.push_back(Copy.takeAs<Expr>());
7821 }
7822
7823 // \brief Reference to the __builtin_memcpy function.
7824 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007825 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007826 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007827
7828 // Assign non-static members.
7829 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7830 FieldEnd = ClassDecl->field_end();
7831 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007832 if (Field->isUnnamedBitfield())
7833 continue;
7834
Douglas Gregor06a9f362010-05-01 20:49:11 +00007835 // Check for members of reference type; we can't copy those.
7836 if (Field->getType()->isReferenceType()) {
7837 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7838 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7839 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007840 Diag(CurrentLocation, diag::note_member_synthesized_at)
7841 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007842 Invalid = true;
7843 continue;
7844 }
7845
7846 // Check for members of const-qualified, non-class type.
7847 QualType BaseType = Context.getBaseElementType(Field->getType());
7848 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7849 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7850 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7851 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007852 Diag(CurrentLocation, diag::note_member_synthesized_at)
7853 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007854 Invalid = true;
7855 continue;
7856 }
John McCallb77115d2011-06-17 00:18:42 +00007857
7858 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007859 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7860 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007861
7862 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007863 if (FieldType->isIncompleteArrayType()) {
7864 assert(ClassDecl->hasFlexibleArrayMember() &&
7865 "Incomplete array type is not valid");
7866 continue;
7867 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007868
7869 // Build references to the field in the object we're copying from and to.
7870 CXXScopeSpec SS; // Intentionally empty
7871 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7872 LookupMemberName);
7873 MemberLookup.addDecl(*Field);
7874 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007875 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007876 Loc, /*IsArrow=*/false,
7877 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007878 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007879 Loc, /*IsArrow=*/true,
7880 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007881 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7882 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7883
7884 // If the field should be copied with __builtin_memcpy rather than via
7885 // explicit assignments, do so. This optimization only applies for arrays
7886 // of scalars and arrays of class type with trivial copy-assignment
7887 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007888 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007889 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007890 // Compute the size of the memory buffer to be copied.
7891 QualType SizeType = Context.getSizeType();
7892 llvm::APInt Size(Context.getTypeSize(SizeType),
7893 Context.getTypeSizeInChars(BaseType).getQuantity());
7894 for (const ConstantArrayType *Array
7895 = Context.getAsConstantArrayType(FieldType);
7896 Array;
7897 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007898 llvm::APInt ArraySize
7899 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007900 Size *= ArraySize;
7901 }
7902
7903 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007904 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7905 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007906
7907 bool NeedsCollectableMemCpy =
7908 (BaseType->isRecordType() &&
7909 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7910
7911 if (NeedsCollectableMemCpy) {
7912 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007913 // Create a reference to the __builtin_objc_memmove_collectable function.
7914 LookupResult R(*this,
7915 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007916 Loc, LookupOrdinaryName);
7917 LookupName(R, TUScope, true);
7918
7919 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7920 if (!CollectableMemCpy) {
7921 // Something went horribly wrong earlier, and we will have
7922 // complained about it.
7923 Invalid = true;
7924 continue;
7925 }
7926
7927 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7928 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007929 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007930 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7931 }
7932 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007933 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007934 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007935 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7936 LookupOrdinaryName);
7937 LookupName(R, TUScope, true);
7938
7939 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7940 if (!BuiltinMemCpy) {
7941 // Something went horribly wrong earlier, and we will have complained
7942 // about it.
7943 Invalid = true;
7944 continue;
7945 }
7946
7947 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7948 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007949 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007950 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7951 }
7952
John McCallca0408f2010-08-23 06:44:23 +00007953 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007954 CallArgs.push_back(To.takeAs<Expr>());
7955 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007956 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007957 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007958 if (NeedsCollectableMemCpy)
7959 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007960 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007961 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007962 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007963 else
7964 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007965 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007966 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007967 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007968
Douglas Gregor06a9f362010-05-01 20:49:11 +00007969 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7970 Statements.push_back(Call.takeAs<Expr>());
7971 continue;
7972 }
7973
7974 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007975 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007976 To.get(), From.get(),
7977 /*CopyingBaseSubobject=*/false,
7978 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007979 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007980 Diag(CurrentLocation, diag::note_member_synthesized_at)
7981 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7982 CopyAssignOperator->setInvalidDecl();
7983 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007984 }
7985
7986 // Success! Record the copy.
7987 Statements.push_back(Copy.takeAs<Stmt>());
7988 }
7989
7990 if (!Invalid) {
7991 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007992 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007993
John McCall60d7b3a2010-08-24 06:29:42 +00007994 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007995 if (Return.isInvalid())
7996 Invalid = true;
7997 else {
7998 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007999
8000 if (Trap.hasErrorOccurred()) {
8001 Diag(CurrentLocation, diag::note_member_synthesized_at)
8002 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8003 Invalid = true;
8004 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008005 }
8006 }
8007
8008 if (Invalid) {
8009 CopyAssignOperator->setInvalidDecl();
8010 return;
8011 }
8012
John McCall60d7b3a2010-08-24 06:29:42 +00008013 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008014 /*isStmtExpr=*/false);
8015 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8016 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008017
8018 if (ASTMutationListener *L = getASTMutationListener()) {
8019 L->CompletedImplicitDefinition(CopyAssignOperator);
8020 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008021}
8022
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008023Sema::ImplicitExceptionSpecification
8024Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8025 ImplicitExceptionSpecification ExceptSpec(Context);
8026
8027 if (ClassDecl->isInvalidDecl())
8028 return ExceptSpec;
8029
8030 // C++0x [except.spec]p14:
8031 // An implicitly declared special member function (Clause 12) shall have an
8032 // exception-specification. [...]
8033
8034 // It is unspecified whether or not an implicit move assignment operator
8035 // attempts to deduplicate calls to assignment operators of virtual bases are
8036 // made. As such, this exception specification is effectively unspecified.
8037 // Based on a similar decision made for constness in C++0x, we're erring on
8038 // the side of assuming such calls to be made regardless of whether they
8039 // actually happen.
8040 // Note that a move constructor is not implicitly declared when there are
8041 // virtual bases, but it can still be user-declared and explicitly defaulted.
8042 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8043 BaseEnd = ClassDecl->bases_end();
8044 Base != BaseEnd; ++Base) {
8045 if (Base->isVirtual())
8046 continue;
8047
8048 CXXRecordDecl *BaseClassDecl
8049 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8050 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8051 false, 0))
8052 ExceptSpec.CalledDecl(MoveAssign);
8053 }
8054
8055 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8056 BaseEnd = ClassDecl->vbases_end();
8057 Base != BaseEnd; ++Base) {
8058 CXXRecordDecl *BaseClassDecl
8059 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8060 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8061 false, 0))
8062 ExceptSpec.CalledDecl(MoveAssign);
8063 }
8064
8065 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8066 FieldEnd = ClassDecl->field_end();
8067 Field != FieldEnd;
8068 ++Field) {
8069 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8070 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8071 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8072 false, 0))
8073 ExceptSpec.CalledDecl(MoveAssign);
8074 }
8075 }
8076
8077 return ExceptSpec;
8078}
8079
8080CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8081 // Note: The following rules are largely analoguous to the move
8082 // constructor rules.
8083
8084 ImplicitExceptionSpecification Spec(
8085 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8086
8087 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8088 QualType RetType = Context.getLValueReferenceType(ArgType);
8089 ArgType = Context.getRValueReferenceType(ArgType);
8090
8091 // An implicitly-declared move assignment operator is an inline public
8092 // member of its class.
8093 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8094 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8095 SourceLocation ClassLoc = ClassDecl->getLocation();
8096 DeclarationNameInfo NameInfo(Name, ClassLoc);
8097 CXXMethodDecl *MoveAssignment
8098 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8099 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8100 /*TInfo=*/0, /*isStatic=*/false,
8101 /*StorageClassAsWritten=*/SC_None,
8102 /*isInline=*/true,
8103 /*isConstexpr=*/false,
8104 SourceLocation());
8105 MoveAssignment->setAccess(AS_public);
8106 MoveAssignment->setDefaulted();
8107 MoveAssignment->setImplicit();
8108 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8109
8110 // Add the parameter to the operator.
8111 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8112 ClassLoc, ClassLoc, /*Id=*/0,
8113 ArgType, /*TInfo=*/0,
8114 SC_None,
8115 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008116 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008117
8118 // Note that we have added this copy-assignment operator.
8119 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8120
8121 // C++0x [class.copy]p9:
8122 // If the definition of a class X does not explicitly declare a move
8123 // assignment operator, one will be implicitly declared as defaulted if and
8124 // only if:
8125 // [...]
8126 // - the move assignment operator would not be implicitly defined as
8127 // deleted.
8128 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8129 // Cache this result so that we don't try to generate this over and over
8130 // on every lookup, leaking memory and wasting time.
8131 ClassDecl->setFailedImplicitMoveAssignment();
8132 return 0;
8133 }
8134
8135 if (Scope *S = getScopeForContext(ClassDecl))
8136 PushOnScopeChains(MoveAssignment, S, false);
8137 ClassDecl->addDecl(MoveAssignment);
8138
8139 AddOverriddenMethods(ClassDecl, MoveAssignment);
8140 return MoveAssignment;
8141}
8142
8143void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8144 CXXMethodDecl *MoveAssignOperator) {
8145 assert((MoveAssignOperator->isDefaulted() &&
8146 MoveAssignOperator->isOverloadedOperator() &&
8147 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8148 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8149 "DefineImplicitMoveAssignment called for wrong function");
8150
8151 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8152
8153 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8154 MoveAssignOperator->setInvalidDecl();
8155 return;
8156 }
8157
8158 MoveAssignOperator->setUsed();
8159
8160 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8161 DiagnosticErrorTrap Trap(Diags);
8162
8163 // C++0x [class.copy]p28:
8164 // The implicitly-defined or move assignment operator for a non-union class
8165 // X performs memberwise move assignment of its subobjects. The direct base
8166 // classes of X are assigned first, in the order of their declaration in the
8167 // base-specifier-list, and then the immediate non-static data members of X
8168 // are assigned, in the order in which they were declared in the class
8169 // definition.
8170
8171 // The statements that form the synthesized function body.
8172 ASTOwningVector<Stmt*> Statements(*this);
8173
8174 // The parameter for the "other" object, which we are move from.
8175 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8176 QualType OtherRefType = Other->getType()->
8177 getAs<RValueReferenceType>()->getPointeeType();
8178 assert(OtherRefType.getQualifiers() == 0 &&
8179 "Bad argument type of defaulted move assignment");
8180
8181 // Our location for everything implicitly-generated.
8182 SourceLocation Loc = MoveAssignOperator->getLocation();
8183
8184 // Construct a reference to the "other" object. We'll be using this
8185 // throughout the generated ASTs.
8186 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8187 assert(OtherRef && "Reference to parameter cannot fail!");
8188 // Cast to rvalue.
8189 OtherRef = CastForMoving(*this, OtherRef);
8190
8191 // Construct the "this" pointer. We'll be using this throughout the generated
8192 // ASTs.
8193 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8194 assert(This && "Reference to this cannot fail!");
8195
8196 // Assign base classes.
8197 bool Invalid = false;
8198 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8199 E = ClassDecl->bases_end(); Base != E; ++Base) {
8200 // Form the assignment:
8201 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8202 QualType BaseType = Base->getType().getUnqualifiedType();
8203 if (!BaseType->isRecordType()) {
8204 Invalid = true;
8205 continue;
8206 }
8207
8208 CXXCastPath BasePath;
8209 BasePath.push_back(Base);
8210
8211 // Construct the "from" expression, which is an implicit cast to the
8212 // appropriately-qualified base type.
8213 Expr *From = OtherRef;
8214 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008215 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008216
8217 // Dereference "this".
8218 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8219
8220 // Implicitly cast "this" to the appropriately-qualified base type.
8221 To = ImpCastExprToType(To.take(),
8222 Context.getCVRQualifiedType(BaseType,
8223 MoveAssignOperator->getTypeQualifiers()),
8224 CK_UncheckedDerivedToBase,
8225 VK_LValue, &BasePath);
8226
8227 // Build the move.
8228 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8229 To.get(), From,
8230 /*CopyingBaseSubobject=*/true,
8231 /*Copying=*/false);
8232 if (Move.isInvalid()) {
8233 Diag(CurrentLocation, diag::note_member_synthesized_at)
8234 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8235 MoveAssignOperator->setInvalidDecl();
8236 return;
8237 }
8238
8239 // Success! Record the move.
8240 Statements.push_back(Move.takeAs<Expr>());
8241 }
8242
8243 // \brief Reference to the __builtin_memcpy function.
8244 Expr *BuiltinMemCpyRef = 0;
8245 // \brief Reference to the __builtin_objc_memmove_collectable function.
8246 Expr *CollectableMemCpyRef = 0;
8247
8248 // Assign non-static members.
8249 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8250 FieldEnd = ClassDecl->field_end();
8251 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008252 if (Field->isUnnamedBitfield())
8253 continue;
8254
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008255 // Check for members of reference type; we can't move those.
8256 if (Field->getType()->isReferenceType()) {
8257 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8258 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8259 Diag(Field->getLocation(), diag::note_declared_at);
8260 Diag(CurrentLocation, diag::note_member_synthesized_at)
8261 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8262 Invalid = true;
8263 continue;
8264 }
8265
8266 // Check for members of const-qualified, non-class type.
8267 QualType BaseType = Context.getBaseElementType(Field->getType());
8268 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8269 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8270 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8271 Diag(Field->getLocation(), diag::note_declared_at);
8272 Diag(CurrentLocation, diag::note_member_synthesized_at)
8273 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8274 Invalid = true;
8275 continue;
8276 }
8277
8278 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008279 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8280 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008281
8282 QualType FieldType = Field->getType().getNonReferenceType();
8283 if (FieldType->isIncompleteArrayType()) {
8284 assert(ClassDecl->hasFlexibleArrayMember() &&
8285 "Incomplete array type is not valid");
8286 continue;
8287 }
8288
8289 // Build references to the field in the object we're copying from and to.
8290 CXXScopeSpec SS; // Intentionally empty
8291 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8292 LookupMemberName);
8293 MemberLookup.addDecl(*Field);
8294 MemberLookup.resolveKind();
8295 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8296 Loc, /*IsArrow=*/false,
8297 SS, 0, MemberLookup, 0);
8298 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8299 Loc, /*IsArrow=*/true,
8300 SS, 0, MemberLookup, 0);
8301 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8302 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8303
8304 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8305 "Member reference with rvalue base must be rvalue except for reference "
8306 "members, which aren't allowed for move assignment.");
8307
8308 // If the field should be copied with __builtin_memcpy rather than via
8309 // explicit assignments, do so. This optimization only applies for arrays
8310 // of scalars and arrays of class type with trivial move-assignment
8311 // operators.
8312 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8313 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8314 // Compute the size of the memory buffer to be copied.
8315 QualType SizeType = Context.getSizeType();
8316 llvm::APInt Size(Context.getTypeSize(SizeType),
8317 Context.getTypeSizeInChars(BaseType).getQuantity());
8318 for (const ConstantArrayType *Array
8319 = Context.getAsConstantArrayType(FieldType);
8320 Array;
8321 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8322 llvm::APInt ArraySize
8323 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8324 Size *= ArraySize;
8325 }
8326
Douglas Gregor45d3d712011-09-01 02:09:07 +00008327 // Take the address of the field references for "from" and "to". We
8328 // directly construct UnaryOperators here because semantic analysis
8329 // does not permit us to take the address of an xvalue.
8330 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8331 Context.getPointerType(From.get()->getType()),
8332 VK_RValue, OK_Ordinary, Loc);
8333 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8334 Context.getPointerType(To.get()->getType()),
8335 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008336
8337 bool NeedsCollectableMemCpy =
8338 (BaseType->isRecordType() &&
8339 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8340
8341 if (NeedsCollectableMemCpy) {
8342 if (!CollectableMemCpyRef) {
8343 // Create a reference to the __builtin_objc_memmove_collectable function.
8344 LookupResult R(*this,
8345 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8346 Loc, LookupOrdinaryName);
8347 LookupName(R, TUScope, true);
8348
8349 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8350 if (!CollectableMemCpy) {
8351 // Something went horribly wrong earlier, and we will have
8352 // complained about it.
8353 Invalid = true;
8354 continue;
8355 }
8356
8357 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8358 CollectableMemCpy->getType(),
8359 VK_LValue, Loc, 0).take();
8360 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8361 }
8362 }
8363 // Create a reference to the __builtin_memcpy builtin function.
8364 else if (!BuiltinMemCpyRef) {
8365 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8366 LookupOrdinaryName);
8367 LookupName(R, TUScope, true);
8368
8369 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8370 if (!BuiltinMemCpy) {
8371 // Something went horribly wrong earlier, and we will have complained
8372 // about it.
8373 Invalid = true;
8374 continue;
8375 }
8376
8377 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8378 BuiltinMemCpy->getType(),
8379 VK_LValue, Loc, 0).take();
8380 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8381 }
8382
8383 ASTOwningVector<Expr*> CallArgs(*this);
8384 CallArgs.push_back(To.takeAs<Expr>());
8385 CallArgs.push_back(From.takeAs<Expr>());
8386 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8387 ExprResult Call = ExprError();
8388 if (NeedsCollectableMemCpy)
8389 Call = ActOnCallExpr(/*Scope=*/0,
8390 CollectableMemCpyRef,
8391 Loc, move_arg(CallArgs),
8392 Loc);
8393 else
8394 Call = ActOnCallExpr(/*Scope=*/0,
8395 BuiltinMemCpyRef,
8396 Loc, move_arg(CallArgs),
8397 Loc);
8398
8399 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8400 Statements.push_back(Call.takeAs<Expr>());
8401 continue;
8402 }
8403
8404 // Build the move of this field.
8405 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8406 To.get(), From.get(),
8407 /*CopyingBaseSubobject=*/false,
8408 /*Copying=*/false);
8409 if (Move.isInvalid()) {
8410 Diag(CurrentLocation, diag::note_member_synthesized_at)
8411 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8412 MoveAssignOperator->setInvalidDecl();
8413 return;
8414 }
8415
8416 // Success! Record the copy.
8417 Statements.push_back(Move.takeAs<Stmt>());
8418 }
8419
8420 if (!Invalid) {
8421 // Add a "return *this;"
8422 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8423
8424 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8425 if (Return.isInvalid())
8426 Invalid = true;
8427 else {
8428 Statements.push_back(Return.takeAs<Stmt>());
8429
8430 if (Trap.hasErrorOccurred()) {
8431 Diag(CurrentLocation, diag::note_member_synthesized_at)
8432 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8433 Invalid = true;
8434 }
8435 }
8436 }
8437
8438 if (Invalid) {
8439 MoveAssignOperator->setInvalidDecl();
8440 return;
8441 }
8442
8443 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8444 /*isStmtExpr=*/false);
8445 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8446 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8447
8448 if (ASTMutationListener *L = getASTMutationListener()) {
8449 L->CompletedImplicitDefinition(MoveAssignOperator);
8450 }
8451}
8452
Sean Hunt49634cf2011-05-13 06:10:58 +00008453std::pair<Sema::ImplicitExceptionSpecification, bool>
8454Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008455 if (ClassDecl->isInvalidDecl())
8456 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8457
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008458 // C++ [class.copy]p5:
8459 // The implicitly-declared copy constructor for a class X will
8460 // have the form
8461 //
8462 // X::X(const X&)
8463 //
8464 // if
Sean Huntc530d172011-06-10 04:44:37 +00008465 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008466 bool HasConstCopyConstructor = true;
8467
8468 // -- each direct or virtual base class B of X has a copy
8469 // constructor whose first parameter is of type const B& or
8470 // const volatile B&, and
8471 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8472 BaseEnd = ClassDecl->bases_end();
8473 HasConstCopyConstructor && Base != BaseEnd;
8474 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008475 // Virtual bases are handled below.
8476 if (Base->isVirtual())
8477 continue;
8478
Douglas Gregor22584312010-07-02 23:41:54 +00008479 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008480 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008481 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8482 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008483 }
8484
8485 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8486 BaseEnd = ClassDecl->vbases_end();
8487 HasConstCopyConstructor && Base != BaseEnd;
8488 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008489 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008490 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008491 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8492 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008493 }
8494
8495 // -- for all the nonstatic data members of X that are of a
8496 // class type M (or array thereof), each such class type
8497 // has a copy constructor whose first parameter is of type
8498 // const M& or const volatile M&.
8499 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8500 FieldEnd = ClassDecl->field_end();
8501 HasConstCopyConstructor && Field != FieldEnd;
8502 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008503 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008504 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008505 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8506 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008507 }
8508 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008509 // Otherwise, the implicitly declared copy constructor will have
8510 // the form
8511 //
8512 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008513
Douglas Gregor0d405db2010-07-01 20:59:04 +00008514 // C++ [except.spec]p14:
8515 // An implicitly declared special member function (Clause 12) shall have an
8516 // exception-specification. [...]
8517 ImplicitExceptionSpecification ExceptSpec(Context);
8518 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8519 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8520 BaseEnd = ClassDecl->bases_end();
8521 Base != BaseEnd;
8522 ++Base) {
8523 // Virtual bases are handled below.
8524 if (Base->isVirtual())
8525 continue;
8526
Douglas Gregor22584312010-07-02 23:41:54 +00008527 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008528 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008529 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008530 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008531 ExceptSpec.CalledDecl(CopyConstructor);
8532 }
8533 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8534 BaseEnd = ClassDecl->vbases_end();
8535 Base != BaseEnd;
8536 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008537 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008538 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008539 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008540 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008541 ExceptSpec.CalledDecl(CopyConstructor);
8542 }
8543 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8544 FieldEnd = ClassDecl->field_end();
8545 Field != FieldEnd;
8546 ++Field) {
8547 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008548 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8549 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008550 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008551 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008552 }
8553 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008554
Sean Hunt49634cf2011-05-13 06:10:58 +00008555 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8556}
8557
8558CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8559 CXXRecordDecl *ClassDecl) {
8560 // C++ [class.copy]p4:
8561 // If the class definition does not explicitly declare a copy
8562 // constructor, one is declared implicitly.
8563
8564 ImplicitExceptionSpecification Spec(Context);
8565 bool Const;
8566 llvm::tie(Spec, Const) =
8567 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8568
8569 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8570 QualType ArgType = ClassType;
8571 if (Const)
8572 ArgType = ArgType.withConst();
8573 ArgType = Context.getLValueReferenceType(ArgType);
8574
8575 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8576
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008577 DeclarationName Name
8578 = Context.DeclarationNames.getCXXConstructorName(
8579 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008580 SourceLocation ClassLoc = ClassDecl->getLocation();
8581 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008582
8583 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008584 // member of its class.
8585 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8586 Context, ClassDecl, ClassLoc, NameInfo,
8587 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8588 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8589 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8590 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008591 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008592 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008593 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008594
Douglas Gregor22584312010-07-02 23:41:54 +00008595 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008596 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8597
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008598 // Add the parameter to the constructor.
8599 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008600 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008601 /*IdentifierInfo=*/0,
8602 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008603 SC_None,
8604 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008605 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008606
Douglas Gregor23c94db2010-07-02 17:43:08 +00008607 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008608 PushOnScopeChains(CopyConstructor, S, false);
8609 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008610
Sean Hunt1ccbc542011-06-22 01:05:13 +00008611 // C++0x [class.copy]p7:
8612 // ... If the class definition declares a move constructor or move
8613 // assignment operator, the implicitly declared constructor is defined as
8614 // deleted; ...
8615 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8616 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Huntc32d6842011-10-11 04:55:36 +00008617 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008618 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008619
8620 return CopyConstructor;
8621}
8622
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008623void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008624 CXXConstructorDecl *CopyConstructor) {
8625 assert((CopyConstructor->isDefaulted() &&
8626 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008627 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008628 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008629
Anders Carlsson63010a72010-04-23 16:24:12 +00008630 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008631 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008632
Douglas Gregor39957dc2010-05-01 15:04:51 +00008633 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008634 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008635
Sean Huntcbb67482011-01-08 20:30:50 +00008636 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008637 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008638 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008639 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008640 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008641 } else {
8642 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8643 CopyConstructor->getLocation(),
8644 MultiStmtArg(*this, 0, 0),
8645 /*isStmtExpr=*/false)
8646 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008647 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008648 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008649
8650 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008651 if (ASTMutationListener *L = getASTMutationListener()) {
8652 L->CompletedImplicitDefinition(CopyConstructor);
8653 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008654}
8655
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008656Sema::ImplicitExceptionSpecification
8657Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8658 // C++ [except.spec]p14:
8659 // An implicitly declared special member function (Clause 12) shall have an
8660 // exception-specification. [...]
8661 ImplicitExceptionSpecification ExceptSpec(Context);
8662 if (ClassDecl->isInvalidDecl())
8663 return ExceptSpec;
8664
8665 // Direct base-class constructors.
8666 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8667 BEnd = ClassDecl->bases_end();
8668 B != BEnd; ++B) {
8669 if (B->isVirtual()) // Handled below.
8670 continue;
8671
8672 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8673 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8674 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8675 // If this is a deleted function, add it anyway. This might be conformant
8676 // with the standard. This might not. I'm not sure. It might not matter.
8677 if (Constructor)
8678 ExceptSpec.CalledDecl(Constructor);
8679 }
8680 }
8681
8682 // Virtual base-class constructors.
8683 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8684 BEnd = ClassDecl->vbases_end();
8685 B != BEnd; ++B) {
8686 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8687 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8688 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8689 // If this is a deleted function, add it anyway. This might be conformant
8690 // with the standard. This might not. I'm not sure. It might not matter.
8691 if (Constructor)
8692 ExceptSpec.CalledDecl(Constructor);
8693 }
8694 }
8695
8696 // Field constructors.
8697 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8698 FEnd = ClassDecl->field_end();
8699 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008700 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008701 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8702 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8703 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8704 // If this is a deleted function, add it anyway. This might be conformant
8705 // with the standard. This might not. I'm not sure. It might not matter.
8706 // In particular, the problem is that this function never gets called. It
8707 // might just be ill-formed because this function attempts to refer to
8708 // a deleted function here.
8709 if (Constructor)
8710 ExceptSpec.CalledDecl(Constructor);
8711 }
8712 }
8713
8714 return ExceptSpec;
8715}
8716
8717CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8718 CXXRecordDecl *ClassDecl) {
8719 ImplicitExceptionSpecification Spec(
8720 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8721
8722 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8723 QualType ArgType = Context.getRValueReferenceType(ClassType);
8724
8725 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8726
8727 DeclarationName Name
8728 = Context.DeclarationNames.getCXXConstructorName(
8729 Context.getCanonicalType(ClassType));
8730 SourceLocation ClassLoc = ClassDecl->getLocation();
8731 DeclarationNameInfo NameInfo(Name, ClassLoc);
8732
8733 // C++0x [class.copy]p11:
8734 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008735 // member of its class.
8736 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8737 Context, ClassDecl, ClassLoc, NameInfo,
8738 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8739 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8740 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8741 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008742 MoveConstructor->setAccess(AS_public);
8743 MoveConstructor->setDefaulted();
8744 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008745
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008746 // Add the parameter to the constructor.
8747 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8748 ClassLoc, ClassLoc,
8749 /*IdentifierInfo=*/0,
8750 ArgType, /*TInfo=*/0,
8751 SC_None,
8752 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008753 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008754
8755 // C++0x [class.copy]p9:
8756 // If the definition of a class X does not explicitly declare a move
8757 // constructor, one will be implicitly declared as defaulted if and only if:
8758 // [...]
8759 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008760 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008761 // Cache this result so that we don't try to generate this over and over
8762 // on every lookup, leaking memory and wasting time.
8763 ClassDecl->setFailedImplicitMoveConstructor();
8764 return 0;
8765 }
8766
8767 // Note that we have declared this constructor.
8768 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8769
8770 if (Scope *S = getScopeForContext(ClassDecl))
8771 PushOnScopeChains(MoveConstructor, S, false);
8772 ClassDecl->addDecl(MoveConstructor);
8773
8774 return MoveConstructor;
8775}
8776
8777void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8778 CXXConstructorDecl *MoveConstructor) {
8779 assert((MoveConstructor->isDefaulted() &&
8780 MoveConstructor->isMoveConstructor() &&
8781 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8782 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8783
8784 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8785 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8786
8787 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8788 DiagnosticErrorTrap Trap(Diags);
8789
8790 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8791 Trap.hasErrorOccurred()) {
8792 Diag(CurrentLocation, diag::note_member_synthesized_at)
8793 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8794 MoveConstructor->setInvalidDecl();
8795 } else {
8796 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8797 MoveConstructor->getLocation(),
8798 MultiStmtArg(*this, 0, 0),
8799 /*isStmtExpr=*/false)
8800 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008801 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008802 }
8803
8804 MoveConstructor->setUsed();
8805
8806 if (ASTMutationListener *L = getASTMutationListener()) {
8807 L->CompletedImplicitDefinition(MoveConstructor);
8808 }
8809}
8810
John McCall60d7b3a2010-08-24 06:29:42 +00008811ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008812Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008813 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008814 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008815 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008816 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008817 unsigned ConstructKind,
8818 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008819 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008820
Douglas Gregor2f599792010-04-02 18:24:57 +00008821 // C++0x [class.copy]p34:
8822 // When certain criteria are met, an implementation is allowed to
8823 // omit the copy/move construction of a class object, even if the
8824 // copy/move constructor and/or destructor for the object have
8825 // side effects. [...]
8826 // - when a temporary class object that has not been bound to a
8827 // reference (12.2) would be copied/moved to a class object
8828 // with the same cv-unqualified type, the copy/move operation
8829 // can be omitted by constructing the temporary object
8830 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008831 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008832 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008833 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008834 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008835 }
Mike Stump1eb44332009-09-09 15:08:12 +00008836
8837 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008838 Elidable, move(ExprArgs), HadMultipleCandidates,
8839 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008840}
8841
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008842/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8843/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008844ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008845Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8846 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008847 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008848 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008849 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008850 unsigned ConstructKind,
8851 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008852 unsigned NumExprs = ExprArgs.size();
8853 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008854
Nick Lewycky909a70d2011-03-25 01:44:32 +00008855 for (specific_attr_iterator<NonNullAttr>
8856 i = Constructor->specific_attr_begin<NonNullAttr>(),
8857 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8858 const NonNullAttr *NonNull = *i;
8859 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8860 }
8861
Douglas Gregor7edfb692009-11-23 12:27:39 +00008862 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008863 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008864 Constructor, Elidable, Exprs, NumExprs,
8865 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008866 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8867 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008868}
8869
Mike Stump1eb44332009-09-09 15:08:12 +00008870bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008871 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008872 MultiExprArg Exprs,
8873 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008874 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008875 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008876 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008877 move(Exprs), HadMultipleCandidates, false,
8878 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008879 if (TempResult.isInvalid())
8880 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008881
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008882 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008883 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008884 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008885 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008886 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008887
Anders Carlssonfe2de492009-08-25 05:18:00 +00008888 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008889}
8890
John McCall68c6c9a2010-02-02 09:10:11 +00008891void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008892 if (VD->isInvalidDecl()) return;
8893
John McCall68c6c9a2010-02-02 09:10:11 +00008894 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008895 if (ClassDecl->isInvalidDecl()) return;
8896 if (ClassDecl->hasTrivialDestructor()) return;
8897 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008898
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008899 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8900 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8901 CheckDestructorAccess(VD->getLocation(), Destructor,
8902 PDiag(diag::err_access_dtor_var)
8903 << VD->getDeclName()
8904 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008905
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008906 if (!VD->hasGlobalStorage()) return;
8907
8908 // Emit warning for non-trivial dtor in global scope (a real global,
8909 // class-static, function-static).
8910 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8911
8912 // TODO: this should be re-enabled for static locals by !CXAAtExit
8913 if (!VD->isStaticLocal())
8914 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008915}
8916
Mike Stump1eb44332009-09-09 15:08:12 +00008917/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008918/// ActOnDeclarator, when a C++ direct initializer is present.
8919/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008920void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008921 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008922 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008923 SourceLocation RParenLoc,
8924 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008925 // If there is no declaration, there was an error parsing it. Just ignore
8926 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008927 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008929
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008930 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8931 if (!VDecl) {
8932 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8933 RealDecl->setInvalidDecl();
8934 return;
8935 }
8936
Eli Friedman6aeaa602012-01-05 22:34:08 +00008937 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00008938 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00008939 if (Exprs.size() == 0) {
8940 // It isn't possible to write this directly, but it is possible to
8941 // end up in this situation with "auto x(some_pack...);"
8942 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
8943 << VDecl->getDeclName() << VDecl->getType()
8944 << VDecl->getSourceRange();
8945 RealDecl->setInvalidDecl();
8946 return;
8947 }
8948
Richard Smith34b41d92011-02-20 03:19:35 +00008949 if (Exprs.size() > 1) {
8950 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8951 diag::err_auto_var_init_multiple_expressions)
8952 << VDecl->getDeclName() << VDecl->getType()
8953 << VDecl->getSourceRange();
8954 RealDecl->setInvalidDecl();
8955 return;
8956 }
8957
8958 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008959 TypeSourceInfo *DeducedType = 0;
8960 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008961 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8962 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8963 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008964 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008965 RealDecl->setInvalidDecl();
8966 return;
8967 }
Richard Smitha085da82011-03-17 16:11:59 +00008968 VDecl->setTypeSourceInfo(DeducedType);
8969 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008970
John McCallf85e1932011-06-15 23:02:42 +00008971 // In ARC, infer lifetime.
8972 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8973 VDecl->setInvalidDecl();
8974
Richard Smith34b41d92011-02-20 03:19:35 +00008975 // If this is a redeclaration, check that the type we just deduced matches
8976 // the previously declared type.
8977 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8978 MergeVarDeclTypes(VDecl, Old);
8979 }
8980
Douglas Gregor83ddad32009-08-26 21:14:46 +00008981 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008982 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008983 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8984 //
8985 // Clients that want to distinguish between the two forms, can check for
8986 // direct initializer using VarDecl::hasCXXDirectInitializer().
8987 // A major benefit is that clients that don't particularly care about which
8988 // exactly form was it (like the CodeGen) can handle both cases without
8989 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008990
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008991 // C++ 8.5p11:
8992 // The form of initialization (using parentheses or '=') is generally
8993 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008994 // class type.
8995
Douglas Gregor4dffad62010-02-11 22:55:30 +00008996 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00008997 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00008998 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00008999 diag::err_typecheck_decl_incomplete_type)) {
9000 VDecl->setInvalidDecl();
9001 return;
9002 }
9003
Douglas Gregor90f93822009-12-22 22:17:25 +00009004 // The variable can not have an abstract class type.
9005 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9006 diag::err_abstract_type_in_decl,
9007 AbstractVariableType))
9008 VDecl->setInvalidDecl();
9009
Sebastian Redl31310a22010-02-01 20:16:42 +00009010 const VarDecl *Def;
9011 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009012 Diag(VDecl->getLocation(), diag::err_redefinition)
9013 << VDecl->getDeclName();
9014 Diag(Def->getLocation(), diag::note_previous_definition);
9015 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009016 return;
9017 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009018
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009019 // C++ [class.static.data]p4
9020 // If a static data member is of const integral or const
9021 // enumeration type, its declaration in the class definition can
9022 // specify a constant-initializer which shall be an integral
9023 // constant expression (5.19). In that case, the member can appear
9024 // in integral constant expressions. The member shall still be
9025 // defined in a namespace scope if it is used in the program and the
9026 // namespace scope definition shall not contain an initializer.
9027 //
9028 // We already performed a redefinition check above, but for static
9029 // data members we also need to check whether there was an in-class
9030 // declaration with an initializer.
9031 const VarDecl* PrevInit = 0;
9032 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9033 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9034 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9035 return;
9036 }
9037
Douglas Gregora31040f2010-12-16 01:31:22 +00009038 bool IsDependent = false;
9039 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9040 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9041 VDecl->setInvalidDecl();
9042 return;
9043 }
9044
9045 if (Exprs.get()[I]->isTypeDependent())
9046 IsDependent = true;
9047 }
9048
Douglas Gregor4dffad62010-02-11 22:55:30 +00009049 // If either the declaration has a dependent type or if any of the
9050 // expressions is type-dependent, we represent the initialization
9051 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009052 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009053 // Let clients know that initialization was done with a direct initializer.
9054 VDecl->setCXXDirectInitializer(true);
9055
9056 // Store the initialization expressions as a ParenListExpr.
9057 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009058 VDecl->setInit(new (Context) ParenListExpr(
9059 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9060 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009061 return;
9062 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009063
9064 // Capture the variable that is being initialized and the style of
9065 // initialization.
9066 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9067
9068 // FIXME: Poor source location information.
9069 InitializationKind Kind
9070 = InitializationKind::CreateDirect(VDecl->getLocation(),
9071 LParenLoc, RParenLoc);
9072
Douglas Gregord24c3062011-10-10 16:05:18 +00009073 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009074 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009075 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009076 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009077 if (Result.isInvalid()) {
9078 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009079 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009080 } else if (T != VDecl->getType()) {
9081 VDecl->setType(T);
9082 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009083 }
John McCallb4eb64d2010-10-08 02:01:28 +00009084
Douglas Gregord24c3062011-10-10 16:05:18 +00009085
Richard Smithc6d990a2011-09-29 19:11:37 +00009086 Expr *Init = Result.get();
9087 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009088
9089 Init = MaybeCreateExprWithCleanups(Init);
9090 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009091 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009092
John McCall2998d6b2011-01-19 11:48:09 +00009093 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009094}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009095
Douglas Gregor39da0b82009-09-09 23:08:42 +00009096/// \brief Given a constructor and the set of arguments provided for the
9097/// constructor, convert the arguments and add any required default arguments
9098/// to form a proper call to this constructor.
9099///
9100/// \returns true if an error occurred, false otherwise.
9101bool
9102Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9103 MultiExprArg ArgsPtr,
9104 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009105 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009106 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9107 unsigned NumArgs = ArgsPtr.size();
9108 Expr **Args = (Expr **)ArgsPtr.get();
9109
9110 const FunctionProtoType *Proto
9111 = Constructor->getType()->getAs<FunctionProtoType>();
9112 assert(Proto && "Constructor without a prototype?");
9113 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009114
9115 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009116 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009117 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009118 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009119 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009120
9121 VariadicCallType CallType =
9122 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009123 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009124 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9125 Proto, 0, Args, NumArgs, AllArgs,
9126 CallType);
9127 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9128 ConvertedArgs.push_back(AllArgs[i]);
9129 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009130}
9131
Anders Carlsson20d45d22009-12-12 00:32:00 +00009132static inline bool
9133CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9134 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009135 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009136 if (isa<NamespaceDecl>(DC)) {
9137 return SemaRef.Diag(FnDecl->getLocation(),
9138 diag::err_operator_new_delete_declared_in_namespace)
9139 << FnDecl->getDeclName();
9140 }
9141
9142 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009143 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009144 return SemaRef.Diag(FnDecl->getLocation(),
9145 diag::err_operator_new_delete_declared_static)
9146 << FnDecl->getDeclName();
9147 }
9148
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009149 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009150}
9151
Anders Carlsson156c78e2009-12-13 17:53:43 +00009152static inline bool
9153CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9154 CanQualType ExpectedResultType,
9155 CanQualType ExpectedFirstParamType,
9156 unsigned DependentParamTypeDiag,
9157 unsigned InvalidParamTypeDiag) {
9158 QualType ResultType =
9159 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9160
9161 // Check that the result type is not dependent.
9162 if (ResultType->isDependentType())
9163 return SemaRef.Diag(FnDecl->getLocation(),
9164 diag::err_operator_new_delete_dependent_result_type)
9165 << FnDecl->getDeclName() << ExpectedResultType;
9166
9167 // Check that the result type is what we expect.
9168 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9169 return SemaRef.Diag(FnDecl->getLocation(),
9170 diag::err_operator_new_delete_invalid_result_type)
9171 << FnDecl->getDeclName() << ExpectedResultType;
9172
9173 // A function template must have at least 2 parameters.
9174 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9175 return SemaRef.Diag(FnDecl->getLocation(),
9176 diag::err_operator_new_delete_template_too_few_parameters)
9177 << FnDecl->getDeclName();
9178
9179 // The function decl must have at least 1 parameter.
9180 if (FnDecl->getNumParams() == 0)
9181 return SemaRef.Diag(FnDecl->getLocation(),
9182 diag::err_operator_new_delete_too_few_parameters)
9183 << FnDecl->getDeclName();
9184
9185 // Check the the first parameter type is not dependent.
9186 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9187 if (FirstParamType->isDependentType())
9188 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9189 << FnDecl->getDeclName() << ExpectedFirstParamType;
9190
9191 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009192 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009193 ExpectedFirstParamType)
9194 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9195 << FnDecl->getDeclName() << ExpectedFirstParamType;
9196
9197 return false;
9198}
9199
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009200static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009201CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009202 // C++ [basic.stc.dynamic.allocation]p1:
9203 // A program is ill-formed if an allocation function is declared in a
9204 // namespace scope other than global scope or declared static in global
9205 // scope.
9206 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9207 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009208
9209 CanQualType SizeTy =
9210 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9211
9212 // C++ [basic.stc.dynamic.allocation]p1:
9213 // The return type shall be void*. The first parameter shall have type
9214 // std::size_t.
9215 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9216 SizeTy,
9217 diag::err_operator_new_dependent_param_type,
9218 diag::err_operator_new_param_type))
9219 return true;
9220
9221 // C++ [basic.stc.dynamic.allocation]p1:
9222 // The first parameter shall not have an associated default argument.
9223 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009224 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009225 diag::err_operator_new_default_arg)
9226 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9227
9228 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009229}
9230
9231static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009232CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9233 // C++ [basic.stc.dynamic.deallocation]p1:
9234 // A program is ill-formed if deallocation functions are declared in a
9235 // namespace scope other than global scope or declared static in global
9236 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009237 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9238 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009239
9240 // C++ [basic.stc.dynamic.deallocation]p2:
9241 // Each deallocation function shall return void and its first parameter
9242 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009243 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9244 SemaRef.Context.VoidPtrTy,
9245 diag::err_operator_delete_dependent_param_type,
9246 diag::err_operator_delete_param_type))
9247 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009248
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009249 return false;
9250}
9251
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009252/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9253/// of this overloaded operator is well-formed. If so, returns false;
9254/// otherwise, emits appropriate diagnostics and returns true.
9255bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009256 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009257 "Expected an overloaded operator declaration");
9258
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009259 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9260
Mike Stump1eb44332009-09-09 15:08:12 +00009261 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009262 // The allocation and deallocation functions, operator new,
9263 // operator new[], operator delete and operator delete[], are
9264 // described completely in 3.7.3. The attributes and restrictions
9265 // found in the rest of this subclause do not apply to them unless
9266 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009267 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009268 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009269
Anders Carlssona3ccda52009-12-12 00:26:23 +00009270 if (Op == OO_New || Op == OO_Array_New)
9271 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009272
9273 // C++ [over.oper]p6:
9274 // An operator function shall either be a non-static member
9275 // function or be a non-member function and have at least one
9276 // parameter whose type is a class, a reference to a class, an
9277 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009278 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9279 if (MethodDecl->isStatic())
9280 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009281 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009282 } else {
9283 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009284 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9285 ParamEnd = FnDecl->param_end();
9286 Param != ParamEnd; ++Param) {
9287 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009288 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9289 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009290 ClassOrEnumParam = true;
9291 break;
9292 }
9293 }
9294
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009295 if (!ClassOrEnumParam)
9296 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009297 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009298 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009299 }
9300
9301 // C++ [over.oper]p8:
9302 // An operator function cannot have default arguments (8.3.6),
9303 // except where explicitly stated below.
9304 //
Mike Stump1eb44332009-09-09 15:08:12 +00009305 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009306 // (C++ [over.call]p1).
9307 if (Op != OO_Call) {
9308 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9309 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009310 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009311 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009312 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009313 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009314 }
9315 }
9316
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009317 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9318 { false, false, false }
9319#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9320 , { Unary, Binary, MemberOnly }
9321#include "clang/Basic/OperatorKinds.def"
9322 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009323
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009324 bool CanBeUnaryOperator = OperatorUses[Op][0];
9325 bool CanBeBinaryOperator = OperatorUses[Op][1];
9326 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009327
9328 // C++ [over.oper]p8:
9329 // [...] Operator functions cannot have more or fewer parameters
9330 // than the number required for the corresponding operator, as
9331 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009332 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009333 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009334 if (Op != OO_Call &&
9335 ((NumParams == 1 && !CanBeUnaryOperator) ||
9336 (NumParams == 2 && !CanBeBinaryOperator) ||
9337 (NumParams < 1) || (NumParams > 2))) {
9338 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009339 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009340 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009341 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009342 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009343 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009344 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009345 assert(CanBeBinaryOperator &&
9346 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009347 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009348 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009349
Chris Lattner416e46f2008-11-21 07:57:12 +00009350 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009351 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009352 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009353
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009354 // Overloaded operators other than operator() cannot be variadic.
9355 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009356 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009357 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009358 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009359 }
9360
9361 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009362 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9363 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009364 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009365 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009366 }
9367
9368 // C++ [over.inc]p1:
9369 // The user-defined function called operator++ implements the
9370 // prefix and postfix ++ operator. If this function is a member
9371 // function with no parameters, or a non-member function with one
9372 // parameter of class or enumeration type, it defines the prefix
9373 // increment operator ++ for objects of that type. If the function
9374 // is a member function with one parameter (which shall be of type
9375 // int) or a non-member function with two parameters (the second
9376 // of which shall be of type int), it defines the postfix
9377 // increment operator ++ for objects of that type.
9378 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9379 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9380 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009381 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009382 ParamIsInt = BT->getKind() == BuiltinType::Int;
9383
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009384 if (!ParamIsInt)
9385 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009386 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009387 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009388 }
9389
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009390 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009391}
Chris Lattner5a003a42008-12-17 07:09:26 +00009392
Sean Hunta6c058d2010-01-13 09:01:02 +00009393/// CheckLiteralOperatorDeclaration - Check whether the declaration
9394/// of this literal operator function is well-formed. If so, returns
9395/// false; otherwise, emits appropriate diagnostics and returns true.
9396bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9397 DeclContext *DC = FnDecl->getDeclContext();
9398 Decl::Kind Kind = DC->getDeclKind();
9399 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9400 Kind != Decl::LinkageSpec) {
9401 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9402 << FnDecl->getDeclName();
9403 return true;
9404 }
9405
9406 bool Valid = false;
9407
Sean Hunt216c2782010-04-07 23:11:06 +00009408 // template <char...> type operator "" name() is the only valid template
9409 // signature, and the only valid signature with no parameters.
9410 if (FnDecl->param_size() == 0) {
9411 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9412 // Must have only one template parameter
9413 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9414 if (Params->size() == 1) {
9415 NonTypeTemplateParmDecl *PmDecl =
9416 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009417
Sean Hunt216c2782010-04-07 23:11:06 +00009418 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009419 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9420 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9421 Valid = true;
9422 }
9423 }
9424 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009425 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009426 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9427
Sean Hunta6c058d2010-01-13 09:01:02 +00009428 QualType T = (*Param)->getType();
9429
Sean Hunt30019c02010-04-07 22:57:35 +00009430 // unsigned long long int, long double, and any character type are allowed
9431 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009432 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9433 Context.hasSameType(T, Context.LongDoubleTy) ||
9434 Context.hasSameType(T, Context.CharTy) ||
9435 Context.hasSameType(T, Context.WCharTy) ||
9436 Context.hasSameType(T, Context.Char16Ty) ||
9437 Context.hasSameType(T, Context.Char32Ty)) {
9438 if (++Param == FnDecl->param_end())
9439 Valid = true;
9440 goto FinishedParams;
9441 }
9442
Sean Hunt30019c02010-04-07 22:57:35 +00009443 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009444 const PointerType *PT = T->getAs<PointerType>();
9445 if (!PT)
9446 goto FinishedParams;
9447 T = PT->getPointeeType();
9448 if (!T.isConstQualified())
9449 goto FinishedParams;
9450 T = T.getUnqualifiedType();
9451
9452 // Move on to the second parameter;
9453 ++Param;
9454
9455 // If there is no second parameter, the first must be a const char *
9456 if (Param == FnDecl->param_end()) {
9457 if (Context.hasSameType(T, Context.CharTy))
9458 Valid = true;
9459 goto FinishedParams;
9460 }
9461
9462 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9463 // are allowed as the first parameter to a two-parameter function
9464 if (!(Context.hasSameType(T, Context.CharTy) ||
9465 Context.hasSameType(T, Context.WCharTy) ||
9466 Context.hasSameType(T, Context.Char16Ty) ||
9467 Context.hasSameType(T, Context.Char32Ty)))
9468 goto FinishedParams;
9469
9470 // The second and final parameter must be an std::size_t
9471 T = (*Param)->getType().getUnqualifiedType();
9472 if (Context.hasSameType(T, Context.getSizeType()) &&
9473 ++Param == FnDecl->param_end())
9474 Valid = true;
9475 }
9476
9477 // FIXME: This diagnostic is absolutely terrible.
9478FinishedParams:
9479 if (!Valid) {
9480 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9481 << FnDecl->getDeclName();
9482 return true;
9483 }
9484
Douglas Gregor1155c422011-08-30 22:40:35 +00009485 StringRef LiteralName
9486 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9487 if (LiteralName[0] != '_') {
9488 // C++0x [usrlit.suffix]p1:
9489 // Literal suffix identifiers that do not start with an underscore are
9490 // reserved for future standardization.
9491 bool IsHexFloat = true;
9492 if (LiteralName.size() > 1 &&
9493 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9494 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9495 if (!isdigit(LiteralName[I])) {
9496 IsHexFloat = false;
9497 break;
9498 }
9499 }
9500 }
9501
9502 if (IsHexFloat)
9503 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9504 << LiteralName;
9505 else
9506 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9507 }
9508
Sean Hunta6c058d2010-01-13 09:01:02 +00009509 return false;
9510}
9511
Douglas Gregor074149e2009-01-05 19:45:36 +00009512/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9513/// linkage specification, including the language and (if present)
9514/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9515/// the location of the language string literal, which is provided
9516/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9517/// the '{' brace. Otherwise, this linkage specification does not
9518/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009519Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9520 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009521 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009522 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009523 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009524 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009525 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009526 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009527 Language = LinkageSpecDecl::lang_cxx;
9528 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009529 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009530 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009531 }
Mike Stump1eb44332009-09-09 15:08:12 +00009532
Chris Lattnercc98eac2008-12-17 07:13:27 +00009533 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009534
Douglas Gregor074149e2009-01-05 19:45:36 +00009535 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009536 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009537 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009538 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009539 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009540}
9541
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009542/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009543/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9544/// valid, it's the position of the closing '}' brace in a linkage
9545/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009546Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009547 Decl *LinkageSpec,
9548 SourceLocation RBraceLoc) {
9549 if (LinkageSpec) {
9550 if (RBraceLoc.isValid()) {
9551 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9552 LSDecl->setRBraceLoc(RBraceLoc);
9553 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009554 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009555 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009556 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009557}
9558
Douglas Gregord308e622009-05-18 20:51:54 +00009559/// \brief Perform semantic analysis for the variable declaration that
9560/// occurs within a C++ catch clause, returning the newly-created
9561/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009562VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009563 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009564 SourceLocation StartLoc,
9565 SourceLocation Loc,
9566 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009567 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009568 QualType ExDeclType = TInfo->getType();
9569
Sebastian Redl4b07b292008-12-22 19:15:10 +00009570 // Arrays and functions decay.
9571 if (ExDeclType->isArrayType())
9572 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9573 else if (ExDeclType->isFunctionType())
9574 ExDeclType = Context.getPointerType(ExDeclType);
9575
9576 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9577 // The exception-declaration shall not denote a pointer or reference to an
9578 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009579 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009580 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009581 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009582 Invalid = true;
9583 }
Douglas Gregord308e622009-05-18 20:51:54 +00009584
Douglas Gregora2762912010-03-08 01:47:36 +00009585 // GCC allows catching pointers and references to incomplete types
9586 // as an extension; so do we, but we warn by default.
9587
Sebastian Redl4b07b292008-12-22 19:15:10 +00009588 QualType BaseType = ExDeclType;
9589 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009590 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009591 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009592 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009593 BaseType = Ptr->getPointeeType();
9594 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009595 DK = diag::ext_catch_incomplete_ptr;
9596 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009597 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009598 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009599 BaseType = Ref->getPointeeType();
9600 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009601 DK = diag::ext_catch_incomplete_ref;
9602 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009603 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009604 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009605 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9606 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009607 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009608
Mike Stump1eb44332009-09-09 15:08:12 +00009609 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009610 RequireNonAbstractType(Loc, ExDeclType,
9611 diag::err_abstract_type_in_decl,
9612 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009613 Invalid = true;
9614
John McCall5a180392010-07-24 00:37:23 +00009615 // Only the non-fragile NeXT runtime currently supports C++ catches
9616 // of ObjC types, and no runtime supports catching ObjC types by value.
9617 if (!Invalid && getLangOptions().ObjC1) {
9618 QualType T = ExDeclType;
9619 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9620 T = RT->getPointeeType();
9621
9622 if (T->isObjCObjectType()) {
9623 Diag(Loc, diag::err_objc_object_catch);
9624 Invalid = true;
9625 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009626 if (!getLangOptions().ObjCNonFragileABI)
9627 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009628 }
9629 }
9630
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009631 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9632 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009633 ExDecl->setExceptionVariable(true);
9634
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009635 // In ARC, infer 'retaining' for variables of retainable type.
9636 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9637 Invalid = true;
9638
Douglas Gregorc41b8782011-07-06 18:14:43 +00009639 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009640 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009641 // C++ [except.handle]p16:
9642 // The object declared in an exception-declaration or, if the
9643 // exception-declaration does not specify a name, a temporary (12.2) is
9644 // copy-initialized (8.5) from the exception object. [...]
9645 // The object is destroyed when the handler exits, after the destruction
9646 // of any automatic objects initialized within the handler.
9647 //
9648 // We just pretend to initialize the object with itself, then make sure
9649 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009650 QualType initType = ExDeclType;
9651
9652 InitializedEntity entity =
9653 InitializedEntity::InitializeVariable(ExDecl);
9654 InitializationKind initKind =
9655 InitializationKind::CreateCopy(Loc, SourceLocation());
9656
9657 Expr *opaqueValue =
9658 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9659 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9660 ExprResult result = sequence.Perform(*this, entity, initKind,
9661 MultiExprArg(&opaqueValue, 1));
9662 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009663 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009664 else {
9665 // If the constructor used was non-trivial, set this as the
9666 // "initializer".
9667 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9668 if (!construct->getConstructor()->isTrivial()) {
9669 Expr *init = MaybeCreateExprWithCleanups(construct);
9670 ExDecl->setInit(init);
9671 }
9672
9673 // And make sure it's destructable.
9674 FinalizeVarWithDestructor(ExDecl, recordType);
9675 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009676 }
9677 }
9678
Douglas Gregord308e622009-05-18 20:51:54 +00009679 if (Invalid)
9680 ExDecl->setInvalidDecl();
9681
9682 return ExDecl;
9683}
9684
9685/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9686/// handler.
John McCalld226f652010-08-21 09:40:31 +00009687Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009688 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009689 bool Invalid = D.isInvalidType();
9690
9691 // Check for unexpanded parameter packs.
9692 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9693 UPPC_ExceptionType)) {
9694 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9695 D.getIdentifierLoc());
9696 Invalid = true;
9697 }
9698
Sebastian Redl4b07b292008-12-22 19:15:10 +00009699 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009700 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009701 LookupOrdinaryName,
9702 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009703 // The scope should be freshly made just for us. There is just no way
9704 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009705 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009706 if (PrevDecl->isTemplateParameter()) {
9707 // Maybe we will complain about the shadowed template parameter.
9708 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009709 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009710 }
9711 }
9712
Chris Lattnereaaebc72009-04-25 08:06:05 +00009713 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009714 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9715 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009716 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009717 }
9718
Douglas Gregor83cb9422010-09-09 17:09:21 +00009719 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009720 D.getSourceRange().getBegin(),
9721 D.getIdentifierLoc(),
9722 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009723 if (Invalid)
9724 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009725
Sebastian Redl4b07b292008-12-22 19:15:10 +00009726 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009727 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009728 PushOnScopeChains(ExDecl, S);
9729 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009730 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009731
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009732 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009733 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009734}
Anders Carlssonfb311762009-03-14 00:25:26 +00009735
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009736Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009737 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009738 Expr *AssertMessageExpr_,
9739 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009740 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009741
Anders Carlssonc3082412009-03-14 00:33:21 +00009742 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009743 llvm::APSInt Cond;
9744 if (VerifyIntegerConstantExpression(AssertExpr, &Cond,
9745 diag::err_static_assert_expression_is_not_constant,
9746 /*AllowFold=*/false))
John McCalld226f652010-08-21 09:40:31 +00009747 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009748
Richard Smithdaaefc52011-12-14 23:32:26 +00009749 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009750 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009751 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009752 }
Mike Stump1eb44332009-09-09 15:08:12 +00009753
Douglas Gregor399ad972010-12-15 23:55:21 +00009754 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9755 return 0;
9756
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009757 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9758 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009759
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009760 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009761 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009762}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009763
Douglas Gregor1d869352010-04-07 16:53:43 +00009764/// \brief Perform semantic analysis of the given friend type declaration.
9765///
9766/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009767FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9768 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009769 TypeSourceInfo *TSInfo) {
9770 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9771
9772 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009773 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009774
Richard Smith6b130222011-10-18 21:39:00 +00009775 // C++03 [class.friend]p2:
9776 // An elaborated-type-specifier shall be used in a friend declaration
9777 // for a class.*
9778 //
9779 // * The class-key of the elaborated-type-specifier is required.
9780 if (!ActiveTemplateInstantiations.empty()) {
9781 // Do not complain about the form of friend template types during
9782 // template instantiation; we will already have complained when the
9783 // template was declared.
9784 } else if (!T->isElaboratedTypeSpecifier()) {
9785 // If we evaluated the type to a record type, suggest putting
9786 // a tag in front.
9787 if (const RecordType *RT = T->getAs<RecordType>()) {
9788 RecordDecl *RD = RT->getDecl();
9789
9790 std::string InsertionText = std::string(" ") + RD->getKindName();
9791
9792 Diag(TypeRange.getBegin(),
9793 getLangOptions().CPlusPlus0x ?
9794 diag::warn_cxx98_compat_unelaborated_friend_type :
9795 diag::ext_unelaborated_friend_type)
9796 << (unsigned) RD->getTagKind()
9797 << T
9798 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9799 InsertionText);
9800 } else {
9801 Diag(FriendLoc,
9802 getLangOptions().CPlusPlus0x ?
9803 diag::warn_cxx98_compat_nonclass_type_friend :
9804 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009805 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009806 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009807 }
Richard Smith6b130222011-10-18 21:39:00 +00009808 } else if (T->getAs<EnumType>()) {
9809 Diag(FriendLoc,
9810 getLangOptions().CPlusPlus0x ?
9811 diag::warn_cxx98_compat_enum_friend :
9812 diag::ext_enum_friend)
9813 << T
9814 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009815 }
9816
Douglas Gregor06245bf2010-04-07 17:57:12 +00009817 // C++0x [class.friend]p3:
9818 // If the type specifier in a friend declaration designates a (possibly
9819 // cv-qualified) class type, that class is declared as a friend; otherwise,
9820 // the friend declaration is ignored.
9821
9822 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9823 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009824
Abramo Bagnara0216df82011-10-29 20:52:52 +00009825 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009826}
9827
John McCall9a34edb2010-10-19 01:40:49 +00009828/// Handle a friend tag declaration where the scope specifier was
9829/// templated.
9830Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9831 unsigned TagSpec, SourceLocation TagLoc,
9832 CXXScopeSpec &SS,
9833 IdentifierInfo *Name, SourceLocation NameLoc,
9834 AttributeList *Attr,
9835 MultiTemplateParamsArg TempParamLists) {
9836 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9837
9838 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009839 bool Invalid = false;
9840
9841 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009842 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009843 TempParamLists.get(),
9844 TempParamLists.size(),
9845 /*friend*/ true,
9846 isExplicitSpecialization,
9847 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009848 if (TemplateParams->size() > 0) {
9849 // This is a declaration of a class template.
9850 if (Invalid)
9851 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009852
Eric Christopher4110e132011-07-21 05:34:24 +00009853 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9854 SS, Name, NameLoc, Attr,
9855 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009856 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009857 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009858 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009859 } else {
9860 // The "template<>" header is extraneous.
9861 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9862 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9863 isExplicitSpecialization = true;
9864 }
9865 }
9866
9867 if (Invalid) return 0;
9868
John McCall9a34edb2010-10-19 01:40:49 +00009869 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009870 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009871 if (TempParamLists.get()[I]->size()) {
9872 isAllExplicitSpecializations = false;
9873 break;
9874 }
9875 }
9876
9877 // FIXME: don't ignore attributes.
9878
9879 // If it's explicit specializations all the way down, just forget
9880 // about the template header and build an appropriate non-templated
9881 // friend. TODO: for source fidelity, remember the headers.
9882 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009883 if (SS.isEmpty()) {
9884 bool Owned = false;
9885 bool IsDependent = false;
9886 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9887 Attr, AS_public,
9888 /*ModulePrivateLoc=*/SourceLocation(),
9889 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009890 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009891 /*ScopedEnumUsesClassTag=*/false,
9892 /*UnderlyingType=*/TypeResult());
9893 }
9894
Douglas Gregor2494dd02011-03-01 01:34:45 +00009895 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009896 ElaboratedTypeKeyword Keyword
9897 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009898 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009899 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009900 if (T.isNull())
9901 return 0;
9902
9903 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9904 if (isa<DependentNameType>(T)) {
9905 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9906 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009907 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009908 TL.setNameLoc(NameLoc);
9909 } else {
9910 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9911 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009912 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009913 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9914 }
9915
9916 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9917 TSI, FriendLoc);
9918 Friend->setAccess(AS_public);
9919 CurContext->addDecl(Friend);
9920 return Friend;
9921 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009922
9923 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9924
9925
John McCall9a34edb2010-10-19 01:40:49 +00009926
9927 // Handle the case of a templated-scope friend class. e.g.
9928 // template <class T> class A<T>::B;
9929 // FIXME: we don't support these right now.
9930 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9931 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9932 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9933 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9934 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009935 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009936 TL.setNameLoc(NameLoc);
9937
9938 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9939 TSI, FriendLoc);
9940 Friend->setAccess(AS_public);
9941 Friend->setUnsupportedFriend(true);
9942 CurContext->addDecl(Friend);
9943 return Friend;
9944}
9945
9946
John McCalldd4a3b02009-09-16 22:47:08 +00009947/// Handle a friend type declaration. This works in tandem with
9948/// ActOnTag.
9949///
9950/// Notes on friend class templates:
9951///
9952/// We generally treat friend class declarations as if they were
9953/// declaring a class. So, for example, the elaborated type specifier
9954/// in a friend declaration is required to obey the restrictions of a
9955/// class-head (i.e. no typedefs in the scope chain), template
9956/// parameters are required to match up with simple template-ids, &c.
9957/// However, unlike when declaring a template specialization, it's
9958/// okay to refer to a template specialization without an empty
9959/// template parameter declaration, e.g.
9960/// friend class A<T>::B<unsigned>;
9961/// We permit this as a special case; if there are any template
9962/// parameters present at all, require proper matching, i.e.
9963/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009964Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009965 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009966 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009967
9968 assert(DS.isFriendSpecified());
9969 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9970
John McCalldd4a3b02009-09-16 22:47:08 +00009971 // Try to convert the decl specifier to a type. This works for
9972 // friend templates because ActOnTag never produces a ClassTemplateDecl
9973 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009974 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009975 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9976 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009977 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009978 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009979
Douglas Gregor6ccab972010-12-16 01:14:37 +00009980 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9981 return 0;
9982
John McCalldd4a3b02009-09-16 22:47:08 +00009983 // This is definitely an error in C++98. It's probably meant to
9984 // be forbidden in C++0x, too, but the specification is just
9985 // poorly written.
9986 //
9987 // The problem is with declarations like the following:
9988 // template <T> friend A<T>::foo;
9989 // where deciding whether a class C is a friend or not now hinges
9990 // on whether there exists an instantiation of A that causes
9991 // 'foo' to equal C. There are restrictions on class-heads
9992 // (which we declare (by fiat) elaborated friend declarations to
9993 // be) that makes this tractable.
9994 //
9995 // FIXME: handle "template <> friend class A<T>;", which
9996 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009997 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009998 Diag(Loc, diag::err_tagless_friend_type_template)
9999 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010000 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010001 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010002
John McCall02cace72009-08-28 07:59:38 +000010003 // C++98 [class.friend]p1: A friend of a class is a function
10004 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010005 // This is fixed in DR77, which just barely didn't make the C++03
10006 // deadline. It's also a very silly restriction that seriously
10007 // affects inner classes and which nobody else seems to implement;
10008 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010009 //
10010 // But note that we could warn about it: it's always useless to
10011 // friend one of your own members (it's not, however, worthless to
10012 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010013
John McCalldd4a3b02009-09-16 22:47:08 +000010014 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010015 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010016 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010017 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010018 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010019 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010020 DS.getFriendSpecLoc());
10021 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010022 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010023
10024 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010025 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010026
John McCalldd4a3b02009-09-16 22:47:08 +000010027 D->setAccess(AS_public);
10028 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010029
John McCalld226f652010-08-21 09:40:31 +000010030 return D;
John McCall02cace72009-08-28 07:59:38 +000010031}
10032
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010033Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010034 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010035 const DeclSpec &DS = D.getDeclSpec();
10036
10037 assert(DS.isFriendSpecified());
10038 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10039
10040 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010041 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010042
10043 // C++ [class.friend]p1
10044 // A friend of a class is a function or class....
10045 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010046 // It *doesn't* see through dependent types, which is correct
10047 // according to [temp.arg.type]p3:
10048 // If a declaration acquires a function type through a
10049 // type dependent on a template-parameter and this causes
10050 // a declaration that does not use the syntactic form of a
10051 // function declarator to have a function type, the program
10052 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010053 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010054 Diag(Loc, diag::err_unexpected_friend);
10055
10056 // It might be worthwhile to try to recover by creating an
10057 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010058 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010059 }
10060
10061 // C++ [namespace.memdef]p3
10062 // - If a friend declaration in a non-local class first declares a
10063 // class or function, the friend class or function is a member
10064 // of the innermost enclosing namespace.
10065 // - The name of the friend is not found by simple name lookup
10066 // until a matching declaration is provided in that namespace
10067 // scope (either before or after the class declaration granting
10068 // friendship).
10069 // - If a friend function is called, its name may be found by the
10070 // name lookup that considers functions from namespaces and
10071 // classes associated with the types of the function arguments.
10072 // - When looking for a prior declaration of a class or a function
10073 // declared as a friend, scopes outside the innermost enclosing
10074 // namespace scope are not considered.
10075
John McCall337ec3d2010-10-12 23:13:28 +000010076 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010077 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10078 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010079 assert(Name);
10080
Douglas Gregor6ccab972010-12-16 01:14:37 +000010081 // Check for unexpanded parameter packs.
10082 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10083 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10084 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10085 return 0;
10086
John McCall67d1a672009-08-06 02:15:43 +000010087 // The context we found the declaration in, or in which we should
10088 // create the declaration.
10089 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010090 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010091 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010092 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010093
John McCall337ec3d2010-10-12 23:13:28 +000010094 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010095
John McCall337ec3d2010-10-12 23:13:28 +000010096 // There are four cases here.
10097 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010098 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010099 // there as appropriate.
10100 // Recover from invalid scope qualifiers as if they just weren't there.
10101 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010102 // C++0x [namespace.memdef]p3:
10103 // If the name in a friend declaration is neither qualified nor
10104 // a template-id and the declaration is a function or an
10105 // elaborated-type-specifier, the lookup to determine whether
10106 // the entity has been previously declared shall not consider
10107 // any scopes outside the innermost enclosing namespace.
10108 // C++0x [class.friend]p11:
10109 // If a friend declaration appears in a local class and the name
10110 // specified is an unqualified name, a prior declaration is
10111 // looked up without considering scopes that are outside the
10112 // innermost enclosing non-class scope. For a friend function
10113 // declaration, if there is no prior declaration, the program is
10114 // ill-formed.
10115 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010116 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010117
John McCall29ae6e52010-10-13 05:45:15 +000010118 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010119 DC = CurContext;
10120 while (true) {
10121 // Skip class contexts. If someone can cite chapter and verse
10122 // for this behavior, that would be nice --- it's what GCC and
10123 // EDG do, and it seems like a reasonable intent, but the spec
10124 // really only says that checks for unqualified existing
10125 // declarations should stop at the nearest enclosing namespace,
10126 // not that they should only consider the nearest enclosing
10127 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010128 while (DC->isRecord())
10129 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010130
John McCall68263142009-11-18 22:49:29 +000010131 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010132
10133 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010134 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010135 break;
John McCall29ae6e52010-10-13 05:45:15 +000010136
John McCall8a407372010-10-14 22:22:28 +000010137 if (isTemplateId) {
10138 if (isa<TranslationUnitDecl>(DC)) break;
10139 } else {
10140 if (DC->isFileContext()) break;
10141 }
John McCall67d1a672009-08-06 02:15:43 +000010142 DC = DC->getParent();
10143 }
10144
10145 // C++ [class.friend]p1: A friend of a class is a function or
10146 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010147 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010148 // Most C++ 98 compilers do seem to give an error here, so
10149 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010150 if (!Previous.empty() && DC->Equals(CurContext))
10151 Diag(DS.getFriendSpecLoc(),
10152 getLangOptions().CPlusPlus0x ?
10153 diag::warn_cxx98_compat_friend_is_member :
10154 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010155
John McCall380aaa42010-10-13 06:22:15 +000010156 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010157
Douglas Gregor883af832011-10-10 01:11:59 +000010158 // C++ [class.friend]p6:
10159 // A function can be defined in a friend declaration of a class if and
10160 // only if the class is a non-local class (9.8), the function name is
10161 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010162 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010163 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10164 }
10165
John McCall337ec3d2010-10-12 23:13:28 +000010166 // - There's a non-dependent scope specifier, in which case we
10167 // compute it and do a previous lookup there for a function
10168 // or function template.
10169 } else if (!SS.getScopeRep()->isDependent()) {
10170 DC = computeDeclContext(SS);
10171 if (!DC) return 0;
10172
10173 if (RequireCompleteDeclContext(SS, DC)) return 0;
10174
10175 LookupQualifiedName(Previous, DC);
10176
10177 // Ignore things found implicitly in the wrong scope.
10178 // TODO: better diagnostics for this case. Suggesting the right
10179 // qualified scope would be nice...
10180 LookupResult::Filter F = Previous.makeFilter();
10181 while (F.hasNext()) {
10182 NamedDecl *D = F.next();
10183 if (!DC->InEnclosingNamespaceSetOf(
10184 D->getDeclContext()->getRedeclContext()))
10185 F.erase();
10186 }
10187 F.done();
10188
10189 if (Previous.empty()) {
10190 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010191 Diag(Loc, diag::err_qualified_friend_not_found)
10192 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010193 return 0;
10194 }
10195
10196 // C++ [class.friend]p1: A friend of a class is a function or
10197 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010198 if (DC->Equals(CurContext))
10199 Diag(DS.getFriendSpecLoc(),
10200 getLangOptions().CPlusPlus0x ?
10201 diag::warn_cxx98_compat_friend_is_member :
10202 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010203
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010204 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010205 // C++ [class.friend]p6:
10206 // A function can be defined in a friend declaration of a class if and
10207 // only if the class is a non-local class (9.8), the function name is
10208 // unqualified, and the function has namespace scope.
10209 SemaDiagnosticBuilder DB
10210 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10211
10212 DB << SS.getScopeRep();
10213 if (DC->isFileContext())
10214 DB << FixItHint::CreateRemoval(SS.getRange());
10215 SS.clear();
10216 }
John McCall337ec3d2010-10-12 23:13:28 +000010217
10218 // - There's a scope specifier that does not match any template
10219 // parameter lists, in which case we use some arbitrary context,
10220 // create a method or method template, and wait for instantiation.
10221 // - There's a scope specifier that does match some template
10222 // parameter lists, which we don't handle right now.
10223 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010224 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010225 // C++ [class.friend]p6:
10226 // A function can be defined in a friend declaration of a class if and
10227 // only if the class is a non-local class (9.8), the function name is
10228 // unqualified, and the function has namespace scope.
10229 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10230 << SS.getScopeRep();
10231 }
10232
John McCall337ec3d2010-10-12 23:13:28 +000010233 DC = CurContext;
10234 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010235 }
Douglas Gregor883af832011-10-10 01:11:59 +000010236
John McCall29ae6e52010-10-13 05:45:15 +000010237 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010238 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010239 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10240 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10241 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010242 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010243 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10244 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010245 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010246 }
John McCall67d1a672009-08-06 02:15:43 +000010247 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010248
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010249 // FIXME: This is an egregious hack to cope with cases where the scope stack
10250 // does not contain the declaration context, i.e., in an out-of-line
10251 // definition of a class.
10252 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10253 if (!DCScope) {
10254 FakeDCScope.setEntity(DC);
10255 DCScope = &FakeDCScope;
10256 }
10257
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010258 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010259 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10260 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010261 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010262
Douglas Gregor182ddf02009-09-28 00:08:27 +000010263 assert(ND->getDeclContext() == DC);
10264 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010265
John McCallab88d972009-08-31 22:39:49 +000010266 // Add the function declaration to the appropriate lookup tables,
10267 // adjusting the redeclarations list as necessary. We don't
10268 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010269 //
John McCallab88d972009-08-31 22:39:49 +000010270 // Also update the scope-based lookup if the target context's
10271 // lookup context is in lexical scope.
10272 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010273 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010274 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010275 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010276 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010277 }
John McCall02cace72009-08-28 07:59:38 +000010278
10279 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010280 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010281 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010282 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010283 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010284
John McCall337ec3d2010-10-12 23:13:28 +000010285 if (ND->isInvalidDecl())
10286 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010287 else {
10288 FunctionDecl *FD;
10289 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10290 FD = FTD->getTemplatedDecl();
10291 else
10292 FD = cast<FunctionDecl>(ND);
10293
10294 // Mark templated-scope function declarations as unsupported.
10295 if (FD->getNumTemplateParameterLists())
10296 FrD->setUnsupportedFriend(true);
10297 }
John McCall337ec3d2010-10-12 23:13:28 +000010298
John McCalld226f652010-08-21 09:40:31 +000010299 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010300}
10301
John McCalld226f652010-08-21 09:40:31 +000010302void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10303 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010304
Sebastian Redl50de12f2009-03-24 22:27:57 +000010305 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10306 if (!Fn) {
10307 Diag(DelLoc, diag::err_deleted_non_function);
10308 return;
10309 }
10310 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
10311 Diag(DelLoc, diag::err_deleted_decl_not_first);
10312 Diag(Prev->getLocation(), diag::note_previous_declaration);
10313 // If the declaration wasn't the first, we delete the function anyway for
10314 // recovery.
10315 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010316 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010317}
Sebastian Redl13e88542009-04-27 21:33:24 +000010318
Sean Hunte4246a62011-05-12 06:15:49 +000010319void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10320 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10321
10322 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010323 if (MD->getParent()->isDependentType()) {
10324 MD->setDefaulted();
10325 MD->setExplicitlyDefaulted();
10326 return;
10327 }
10328
Sean Hunte4246a62011-05-12 06:15:49 +000010329 CXXSpecialMember Member = getSpecialMember(MD);
10330 if (Member == CXXInvalid) {
10331 Diag(DefaultLoc, diag::err_default_special_members);
10332 return;
10333 }
10334
10335 MD->setDefaulted();
10336 MD->setExplicitlyDefaulted();
10337
Sean Huntcd10dec2011-05-23 23:14:04 +000010338 // If this definition appears within the record, do the checking when
10339 // the record is complete.
10340 const FunctionDecl *Primary = MD;
10341 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10342 // Find the uninstantiated declaration that actually had the '= default'
10343 // on it.
10344 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10345
10346 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010347 return;
10348
10349 switch (Member) {
10350 case CXXDefaultConstructor: {
10351 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10352 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010353 if (!CD->isInvalidDecl())
10354 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10355 break;
10356 }
10357
10358 case CXXCopyConstructor: {
10359 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10360 CheckExplicitlyDefaultedCopyConstructor(CD);
10361 if (!CD->isInvalidDecl())
10362 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010363 break;
10364 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010365
Sean Hunt2b188082011-05-14 05:23:28 +000010366 case CXXCopyAssignment: {
10367 CheckExplicitlyDefaultedCopyAssignment(MD);
10368 if (!MD->isInvalidDecl())
10369 DefineImplicitCopyAssignment(DefaultLoc, MD);
10370 break;
10371 }
10372
Sean Huntcb45a0f2011-05-12 22:46:25 +000010373 case CXXDestructor: {
10374 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10375 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010376 if (!DD->isInvalidDecl())
10377 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010378 break;
10379 }
10380
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010381 case CXXMoveConstructor: {
10382 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10383 CheckExplicitlyDefaultedMoveConstructor(CD);
10384 if (!CD->isInvalidDecl())
10385 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010386 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010387 }
Sean Hunt82713172011-05-25 23:16:36 +000010388
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010389 case CXXMoveAssignment: {
10390 CheckExplicitlyDefaultedMoveAssignment(MD);
10391 if (!MD->isInvalidDecl())
10392 DefineImplicitMoveAssignment(DefaultLoc, MD);
10393 break;
10394 }
10395
10396 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010397 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010398 }
10399 } else {
10400 Diag(DefaultLoc, diag::err_default_special_members);
10401 }
10402}
10403
Sebastian Redl13e88542009-04-27 21:33:24 +000010404static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010405 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010406 Stmt *SubStmt = *CI;
10407 if (!SubStmt)
10408 continue;
10409 if (isa<ReturnStmt>(SubStmt))
10410 Self.Diag(SubStmt->getSourceRange().getBegin(),
10411 diag::err_return_in_constructor_handler);
10412 if (!isa<Expr>(SubStmt))
10413 SearchForReturnInStmt(Self, SubStmt);
10414 }
10415}
10416
10417void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10418 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10419 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10420 SearchForReturnInStmt(*this, Handler);
10421 }
10422}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010423
Mike Stump1eb44332009-09-09 15:08:12 +000010424bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010425 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010426 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10427 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010428
Chandler Carruth73857792010-02-15 11:53:20 +000010429 if (Context.hasSameType(NewTy, OldTy) ||
10430 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010431 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010432
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010433 // Check if the return types are covariant
10434 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010435
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010436 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010437 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10438 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010439 NewClassTy = NewPT->getPointeeType();
10440 OldClassTy = OldPT->getPointeeType();
10441 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010442 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10443 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10444 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10445 NewClassTy = NewRT->getPointeeType();
10446 OldClassTy = OldRT->getPointeeType();
10447 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010448 }
10449 }
Mike Stump1eb44332009-09-09 15:08:12 +000010450
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010451 // The return types aren't either both pointers or references to a class type.
10452 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010453 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010454 diag::err_different_return_type_for_overriding_virtual_function)
10455 << New->getDeclName() << NewTy << OldTy;
10456 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010457
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010458 return true;
10459 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010460
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010461 // C++ [class.virtual]p6:
10462 // If the return type of D::f differs from the return type of B::f, the
10463 // class type in the return type of D::f shall be complete at the point of
10464 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010465 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10466 if (!RT->isBeingDefined() &&
10467 RequireCompleteType(New->getLocation(), NewClassTy,
10468 PDiag(diag::err_covariant_return_incomplete)
10469 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010470 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010471 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010472
Douglas Gregora4923eb2009-11-16 21:35:15 +000010473 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010474 // Check if the new class derives from the old class.
10475 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10476 Diag(New->getLocation(),
10477 diag::err_covariant_return_not_derived)
10478 << New->getDeclName() << NewTy << OldTy;
10479 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10480 return true;
10481 }
Mike Stump1eb44332009-09-09 15:08:12 +000010482
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010483 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010484 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010485 diag::err_covariant_return_inaccessible_base,
10486 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10487 // FIXME: Should this point to the return type?
10488 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010489 // FIXME: this note won't trigger for delayed access control
10490 // diagnostics, and it's impossible to get an undelayed error
10491 // here from access control during the original parse because
10492 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010493 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10494 return true;
10495 }
10496 }
Mike Stump1eb44332009-09-09 15:08:12 +000010497
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010498 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010499 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010500 Diag(New->getLocation(),
10501 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010502 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010503 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10504 return true;
10505 };
Mike Stump1eb44332009-09-09 15:08:12 +000010506
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010507
10508 // The new class type must have the same or less qualifiers as the old type.
10509 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10510 Diag(New->getLocation(),
10511 diag::err_covariant_return_type_class_type_more_qualified)
10512 << New->getDeclName() << NewTy << OldTy;
10513 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10514 return true;
10515 };
Mike Stump1eb44332009-09-09 15:08:12 +000010516
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010517 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010518}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010519
Douglas Gregor4ba31362009-12-01 17:24:26 +000010520/// \brief Mark the given method pure.
10521///
10522/// \param Method the method to be marked pure.
10523///
10524/// \param InitRange the source range that covers the "0" initializer.
10525bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010526 SourceLocation EndLoc = InitRange.getEnd();
10527 if (EndLoc.isValid())
10528 Method->setRangeEnd(EndLoc);
10529
Douglas Gregor4ba31362009-12-01 17:24:26 +000010530 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10531 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010532 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010533 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010534
10535 if (!Method->isInvalidDecl())
10536 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10537 << Method->getDeclName() << InitRange;
10538 return true;
10539}
10540
John McCall731ad842009-12-19 09:28:58 +000010541/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10542/// an initializer for the out-of-line declaration 'Dcl'. The scope
10543/// is a fresh scope pushed for just this purpose.
10544///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010545/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10546/// static data member of class X, names should be looked up in the scope of
10547/// class X.
John McCalld226f652010-08-21 09:40:31 +000010548void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010549 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010550 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010551
John McCall731ad842009-12-19 09:28:58 +000010552 // We should only get called for declarations with scope specifiers, like:
10553 // int foo::bar;
10554 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010555 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010556}
10557
10558/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010559/// initializer for the out-of-line declaration 'D'.
10560void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010561 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010562 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010563
John McCall731ad842009-12-19 09:28:58 +000010564 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010565 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010566}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010567
10568/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10569/// C++ if/switch/while/for statement.
10570/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010571DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010572 // C++ 6.4p2:
10573 // The declarator shall not specify a function or an array.
10574 // The type-specifier-seq shall not contain typedef and shall not declare a
10575 // new class or enumeration.
10576 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10577 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010578
10579 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010580 if (!Dcl)
10581 return true;
10582
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010583 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10584 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010585 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010586 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010587 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010588
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010589 return Dcl;
10590}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010591
Douglas Gregordfe65432011-07-28 19:11:31 +000010592void Sema::LoadExternalVTableUses() {
10593 if (!ExternalSource)
10594 return;
10595
10596 SmallVector<ExternalVTableUse, 4> VTables;
10597 ExternalSource->ReadUsedVTables(VTables);
10598 SmallVector<VTableUse, 4> NewUses;
10599 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10600 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10601 = VTablesUsed.find(VTables[I].Record);
10602 // Even if a definition wasn't required before, it may be required now.
10603 if (Pos != VTablesUsed.end()) {
10604 if (!Pos->second && VTables[I].DefinitionRequired)
10605 Pos->second = true;
10606 continue;
10607 }
10608
10609 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10610 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10611 }
10612
10613 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10614}
10615
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010616void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10617 bool DefinitionRequired) {
10618 // Ignore any vtable uses in unevaluated operands or for classes that do
10619 // not have a vtable.
10620 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10621 CurContext->isDependentContext() ||
Richard Smithf6702a32011-12-20 02:08:33 +000010622 ExprEvalContexts.back().Context == Unevaluated ||
10623 ExprEvalContexts.back().Context == ConstantEvaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010624 return;
10625
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010626 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010627 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010628 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10629 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10630 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10631 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010632 // If we already had an entry, check to see if we are promoting this vtable
10633 // to required a definition. If so, we need to reappend to the VTableUses
10634 // list, since we may have already processed the first entry.
10635 if (DefinitionRequired && !Pos.first->second) {
10636 Pos.first->second = true;
10637 } else {
10638 // Otherwise, we can early exit.
10639 return;
10640 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010641 }
10642
10643 // Local classes need to have their virtual members marked
10644 // immediately. For all other classes, we mark their virtual members
10645 // at the end of the translation unit.
10646 if (Class->isLocalClass())
10647 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010648 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010649 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010650}
10651
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010652bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010653 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010654 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010655 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010656
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010657 // Note: The VTableUses vector could grow as a result of marking
10658 // the members of a class as "used", so we check the size each
10659 // time through the loop and prefer indices (with are stable) to
10660 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010661 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010662 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010663 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010664 if (!Class)
10665 continue;
10666
10667 SourceLocation Loc = VTableUses[I].second;
10668
10669 // If this class has a key function, but that key function is
10670 // defined in another translation unit, we don't need to emit the
10671 // vtable even though we're using it.
10672 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010673 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010674 switch (KeyFunction->getTemplateSpecializationKind()) {
10675 case TSK_Undeclared:
10676 case TSK_ExplicitSpecialization:
10677 case TSK_ExplicitInstantiationDeclaration:
10678 // The key function is in another translation unit.
10679 continue;
10680
10681 case TSK_ExplicitInstantiationDefinition:
10682 case TSK_ImplicitInstantiation:
10683 // We will be instantiating the key function.
10684 break;
10685 }
10686 } else if (!KeyFunction) {
10687 // If we have a class with no key function that is the subject
10688 // of an explicit instantiation declaration, suppress the
10689 // vtable; it will live with the explicit instantiation
10690 // definition.
10691 bool IsExplicitInstantiationDeclaration
10692 = Class->getTemplateSpecializationKind()
10693 == TSK_ExplicitInstantiationDeclaration;
10694 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10695 REnd = Class->redecls_end();
10696 R != REnd; ++R) {
10697 TemplateSpecializationKind TSK
10698 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10699 if (TSK == TSK_ExplicitInstantiationDeclaration)
10700 IsExplicitInstantiationDeclaration = true;
10701 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10702 IsExplicitInstantiationDeclaration = false;
10703 break;
10704 }
10705 }
10706
10707 if (IsExplicitInstantiationDeclaration)
10708 continue;
10709 }
10710
10711 // Mark all of the virtual members of this class as referenced, so
10712 // that we can build a vtable. Then, tell the AST consumer that a
10713 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010714 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010715 MarkVirtualMembersReferenced(Loc, Class);
10716 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10717 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10718
10719 // Optionally warn if we're emitting a weak vtable.
10720 if (Class->getLinkage() == ExternalLinkage &&
10721 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010722 const FunctionDecl *KeyFunctionDef = 0;
10723 if (!KeyFunction ||
10724 (KeyFunction->hasBody(KeyFunctionDef) &&
10725 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010726 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10727 TSK_ExplicitInstantiationDefinition
10728 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10729 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010730 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010731 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010732 VTableUses.clear();
10733
Douglas Gregor78844032011-04-22 22:25:37 +000010734 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010735}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010736
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010737void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10738 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010739 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10740 e = RD->method_end(); i != e; ++i) {
10741 CXXMethodDecl *MD = *i;
10742
10743 // C++ [basic.def.odr]p2:
10744 // [...] A virtual member function is used if it is not pure. [...]
10745 if (MD->isVirtual() && !MD->isPure())
10746 MarkDeclarationReferenced(Loc, MD);
10747 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010748
10749 // Only classes that have virtual bases need a VTT.
10750 if (RD->getNumVBases() == 0)
10751 return;
10752
10753 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10754 e = RD->bases_end(); i != e; ++i) {
10755 const CXXRecordDecl *Base =
10756 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010757 if (Base->getNumVBases() == 0)
10758 continue;
10759 MarkVirtualMembersReferenced(Loc, Base);
10760 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010761}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010762
10763/// SetIvarInitializers - This routine builds initialization ASTs for the
10764/// Objective-C implementation whose ivars need be initialized.
10765void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10766 if (!getLangOptions().CPlusPlus)
10767 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010768 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010769 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010770 CollectIvarsToConstructOrDestruct(OID, ivars);
10771 if (ivars.empty())
10772 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010773 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010774 for (unsigned i = 0; i < ivars.size(); i++) {
10775 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010776 if (Field->isInvalidDecl())
10777 continue;
10778
Sean Huntcbb67482011-01-08 20:30:50 +000010779 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010780 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10781 InitializationKind InitKind =
10782 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10783
10784 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010785 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010786 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010787 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010788 // Note, MemberInit could actually come back empty if no initialization
10789 // is required (e.g., because it would call a trivial default constructor)
10790 if (!MemberInit.get() || MemberInit.isInvalid())
10791 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010792
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010793 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010794 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10795 SourceLocation(),
10796 MemberInit.takeAs<Expr>(),
10797 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010798 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010799
10800 // Be sure that the destructor is accessible and is marked as referenced.
10801 if (const RecordType *RecordTy
10802 = Context.getBaseElementType(Field->getType())
10803 ->getAs<RecordType>()) {
10804 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010805 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010806 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10807 CheckDestructorAccess(Field->getLocation(), Destructor,
10808 PDiag(diag::err_access_dtor_ivar)
10809 << Context.getBaseElementType(Field->getType()));
10810 }
10811 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010812 }
10813 ObjCImplementation->setIvarInitializers(Context,
10814 AllToInit.data(), AllToInit.size());
10815 }
10816}
Sean Huntfe57eef2011-05-04 05:57:24 +000010817
Sean Huntebcbe1d2011-05-04 23:29:54 +000010818static
10819void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10820 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10821 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10822 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10823 Sema &S) {
10824 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10825 CE = Current.end();
10826 if (Ctor->isInvalidDecl())
10827 return;
10828
10829 const FunctionDecl *FNTarget = 0;
10830 CXXConstructorDecl *Target;
10831
10832 // We ignore the result here since if we don't have a body, Target will be
10833 // null below.
10834 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10835 Target
10836= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10837
10838 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10839 // Avoid dereferencing a null pointer here.
10840 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10841
10842 if (!Current.insert(Canonical))
10843 return;
10844
10845 // We know that beyond here, we aren't chaining into a cycle.
10846 if (!Target || !Target->isDelegatingConstructor() ||
10847 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10848 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10849 Valid.insert(*CI);
10850 Current.clear();
10851 // We've hit a cycle.
10852 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10853 Current.count(TCanonical)) {
10854 // If we haven't diagnosed this cycle yet, do so now.
10855 if (!Invalid.count(TCanonical)) {
10856 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010857 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010858 << Ctor;
10859
10860 // Don't add a note for a function delegating directo to itself.
10861 if (TCanonical != Canonical)
10862 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10863
10864 CXXConstructorDecl *C = Target;
10865 while (C->getCanonicalDecl() != Canonical) {
10866 (void)C->getTargetConstructor()->hasBody(FNTarget);
10867 assert(FNTarget && "Ctor cycle through bodiless function");
10868
10869 C
10870 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10871 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10872 }
10873 }
10874
10875 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10876 Invalid.insert(*CI);
10877 Current.clear();
10878 } else {
10879 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10880 }
10881}
10882
10883
Sean Huntfe57eef2011-05-04 05:57:24 +000010884void Sema::CheckDelegatingCtorCycles() {
10885 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10886
Sean Huntebcbe1d2011-05-04 23:29:54 +000010887 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10888 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010889
Douglas Gregor0129b562011-07-27 21:57:17 +000010890 for (DelegatingCtorDeclsType::iterator
10891 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010892 E = DelegatingCtorDecls.end();
10893 I != E; ++I) {
10894 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010895 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010896
10897 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10898 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010899}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010900
10901/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10902Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10903 // Implicitly declared functions (e.g. copy constructors) are
10904 // __host__ __device__
10905 if (D->isImplicit())
10906 return CFT_HostDevice;
10907
10908 if (D->hasAttr<CUDAGlobalAttr>())
10909 return CFT_Global;
10910
10911 if (D->hasAttr<CUDADeviceAttr>()) {
10912 if (D->hasAttr<CUDAHostAttr>())
10913 return CFT_HostDevice;
10914 else
10915 return CFT_Device;
10916 }
10917
10918 return CFT_Host;
10919}
10920
10921bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10922 CUDAFunctionTarget CalleeTarget) {
10923 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10924 // Callable from the device only."
10925 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10926 return true;
10927
10928 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10929 // Callable from the host only."
10930 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10931 // Callable from the host only."
10932 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10933 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10934 return true;
10935
10936 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10937 return true;
10938
10939 return false;
10940}