blob: 3acbb98ebd93c29474ea5d94aa7a37b704ad2e38 [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;
395 if (getLangOptions().Microsoft) {
396 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
Douglas Gregore13ad832010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000507
Douglas Gregorcda9c672009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000509}
510
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551}
552
Chris Lattner3d1cee32008-04-08 05:04:30 +0000553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000583 else
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604
Douglas Gregorb48fe382008-10-31 09:07:45 +0000605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000680 return 0;
John McCall572fc622010-08-17 07:23:57 +0000681 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000682
Eli Friedman1d954f62009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000690
Anders Carlsson1d209272011-03-25 14:55:14 +0000691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
John McCall572fc622010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000709}
710
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000716BaseResult
John McCalld226f652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregor40808ce2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky56062202010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000731
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000736
Douglas Gregor2943aed2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregor2943aed2009-03-03 04:44:36 +0000742 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000743}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000744
Douglas Gregor2943aed2009-03-03 04:44:36 +0000745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
John McCalld226f652010-08-21 09:40:31 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000809
John McCall3cb0ebd2010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregora8f32e02009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 return false;
828
John McCall3cb0ebd2010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000831 return false;
832
John McCall86ff3082010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCall3cb0ebd2010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 return false;
846
John McCall3cb0ebd2010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregora8f32e02009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000875}
876
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregora8f32e02009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000926 }
John McCall6b2accb2010-02-10 09:31:12 +0000927 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnara6206d532010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +00001016}
1017
Anders Carlsson9e682d92011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001020 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlsson9e682d92011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001063 Expr *BW, const VirtSpecifiers &VS,
1064 Expr *InitExpr, bool HasDeferredInit,
Richard Smith7a614d82011-06-11 17:19:42 +00001065 bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001077
John McCall4bde1e12010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith7a614d82011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall67d1a672009-08-06 02:15:43 +00001081
Richard Smith1ab0d902011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001083
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001099 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Sebastian Redla11f42f2008-11-17 23:24:37 +00001102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
Sebastian Redl669d5d72008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregor922fff22010-10-13 22:19:53 +00001124 if (SS.isSet() && !SS.isInvalid()) {
1125 // The user provided a superfluous scope specifier inside a class
1126 // definition:
1127 //
1128 // class X {
1129 // int X::member;
1130 // };
1131 DeclContext *DC = 0;
1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134 << Name << FixItHint::CreateRemoval(SS.getRange());
1135 else
1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137 << Name << SS.getRange();
1138
1139 SS.clear();
1140 }
1141
Douglas Gregor37b372b2009-08-20 22:52:58 +00001142 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001143 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001145 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001146 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001147 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001148 assert(!HasDeferredInit);
1149
Sean Hunte4246a62011-05-12 06:15:49 +00001150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001151 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001152 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001153 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001154
1155 // Non-instance-fields can't have a bitfield.
1156 if (BitWidth) {
1157 if (Member->isInvalidDecl()) {
1158 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001159 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001160 // C++ 9.6p3: A bit-field shall not be a static member.
1161 // "static member 'A' cannot be a bit-field"
1162 Diag(Loc, diag::err_static_not_bitfield)
1163 << Name << BitWidth->getSourceRange();
1164 } else if (isa<TypedefDecl>(Member)) {
1165 // "typedef member 'x' cannot be a bit-field"
1166 Diag(Loc, diag::err_typedef_not_bitfield)
1167 << Name << BitWidth->getSourceRange();
1168 } else {
1169 // A function typedef ("typedef int f(); f a;").
1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001172 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001173 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner8b963ef2009-03-05 23:01:03 +00001176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001179
1180 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Douglas Gregor37b372b2009-08-20 22:52:58 +00001182 // If we have declared a member function template, set the access of the
1183 // templated declaration as well.
1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001186 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001187
Anders Carlssonaae5af22011-01-20 04:34:22 +00001188 if (VS.isOverrideSpecified()) {
1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190 if (!MD || !MD->isVirtual()) {
1191 Diag(Member->getLocStart(),
1192 diag::override_keyword_only_allowed_on_virtual_member_functions)
1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001194 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001196 }
1197 if (VS.isFinalSpecified()) {
1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199 if (!MD || !MD->isVirtual()) {
1200 Diag(Member->getLocStart(),
1201 diag::override_keyword_only_allowed_on_virtual_member_functions)
1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001203 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001205 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001206
Douglas Gregorf5251602011-03-08 17:10:18 +00001207 if (VS.getLastLocation().isValid()) {
1208 // Update the end location of a method that has a virt-specifiers.
1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210 MD->setRangeEnd(VS.getLastLocation());
1211 }
1212
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001213 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001214
Douglas Gregor10bd3682008-11-17 22:58:34 +00001215 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001216
Douglas Gregor021c3b32009-03-11 23:00:04 +00001217 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith7a614d82011-06-11 17:19:42 +00001220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223 // data member if a brace-or-equal-initializer is provided.
1224 Diag(Loc, diag::err_auto_var_requires_init)
1225 << Name << cast<ValueDecl>(Member)->getType();
1226 Member->setInvalidDecl();
1227 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001228
Richard Smith483b9f32011-02-21 20:05:19 +00001229 FinalizeDeclaration(Member);
1230
John McCallb25b2952011-02-15 07:12:36 +00001231 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001232 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001233 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001234}
1235
Richard Smith7a614d82011-06-11 17:19:42 +00001236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001237/// in-class initializer for a non-static C++ class member, and after
1238/// instantiating an in-class initializer in a class template. Such actions
1239/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001240void
1241Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1242 Expr *InitExpr) {
1243 FieldDecl *FD = cast<FieldDecl>(D);
1244
1245 if (!InitExpr) {
1246 FD->setInvalidDecl();
1247 FD->removeInClassInitializer();
1248 return;
1249 }
1250
1251 ExprResult Init = InitExpr;
1252 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1253 // FIXME: if there is no EqualLoc, this is list-initialization.
1254 Init = PerformCopyInitialization(
1255 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1256 if (Init.isInvalid()) {
1257 FD->setInvalidDecl();
1258 return;
1259 }
1260
1261 CheckImplicitConversions(Init.get(), EqualLoc);
1262 }
1263
1264 // C++0x [class.base.init]p7:
1265 // The initialization of each base and member constitutes a
1266 // full-expression.
1267 Init = MaybeCreateExprWithCleanups(Init);
1268 if (Init.isInvalid()) {
1269 FD->setInvalidDecl();
1270 return;
1271 }
1272
1273 InitExpr = Init.release();
1274
1275 FD->setInClassInitializer(InitExpr);
1276}
1277
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001278/// \brief Find the direct and/or virtual base specifiers that
1279/// correspond to the given base type, for use in base initialization
1280/// within a constructor.
1281static bool FindBaseInitializer(Sema &SemaRef,
1282 CXXRecordDecl *ClassDecl,
1283 QualType BaseType,
1284 const CXXBaseSpecifier *&DirectBaseSpec,
1285 const CXXBaseSpecifier *&VirtualBaseSpec) {
1286 // First, check for a direct base class.
1287 DirectBaseSpec = 0;
1288 for (CXXRecordDecl::base_class_const_iterator Base
1289 = ClassDecl->bases_begin();
1290 Base != ClassDecl->bases_end(); ++Base) {
1291 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1292 // We found a direct base of this type. That's what we're
1293 // initializing.
1294 DirectBaseSpec = &*Base;
1295 break;
1296 }
1297 }
1298
1299 // Check for a virtual base class.
1300 // FIXME: We might be able to short-circuit this if we know in advance that
1301 // there are no virtual bases.
1302 VirtualBaseSpec = 0;
1303 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1304 // We haven't found a base yet; search the class hierarchy for a
1305 // virtual base class.
1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307 /*DetectVirtual=*/false);
1308 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1309 BaseType, Paths)) {
1310 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1311 Path != Paths.end(); ++Path) {
1312 if (Path->back().Base->isVirtual()) {
1313 VirtualBaseSpec = Path->back().Base;
1314 break;
1315 }
1316 }
1317 }
1318 }
1319
1320 return DirectBaseSpec || VirtualBaseSpec;
1321}
1322
Douglas Gregor7ad83902008-11-05 04:29:56 +00001323/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001324MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001325Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001326 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001327 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001328 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001329 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001330 SourceLocation IdLoc,
1331 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001332 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001333 SourceLocation RParenLoc,
1334 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001335 if (!ConstructorD)
1336 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001338 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001339
1340 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001341 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001342 if (!Constructor) {
1343 // The user wrote a constructor initializer on a function that is
1344 // not a C++ constructor. Ignore the error for now, because we may
1345 // have more member initializers coming; we'll diagnose it just
1346 // once in ActOnMemInitializers.
1347 return true;
1348 }
1349
1350 CXXRecordDecl *ClassDecl = Constructor->getParent();
1351
1352 // C++ [class.base.init]p2:
1353 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001354 // constructor's class and, if not found in that scope, are looked
1355 // up in the scope containing the constructor's definition.
1356 // [Note: if the constructor's class contains a member with the
1357 // same name as a direct or virtual base class of the class, a
1358 // mem-initializer-id naming the member or base class and composed
1359 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001360 // mem-initializer-id for the hidden base class may be specified
1361 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001362 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001363 // Look for a member, first.
1364 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001365 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001366 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001367 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001368 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001369
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001370 if (Member) {
1371 if (EllipsisLoc.isValid())
1372 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1373 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1374
Francois Pichet00eb3f92010-12-04 09:14:42 +00001375 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001376 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001377 }
1378
Francois Pichet00eb3f92010-12-04 09:14:42 +00001379 // Handle anonymous union case.
1380 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001381 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1382 if (EllipsisLoc.isValid())
1383 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1384 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1385
Francois Pichet00eb3f92010-12-04 09:14:42 +00001386 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1387 NumArgs, IdLoc,
1388 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001389 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001390 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001391 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001392 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001393 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001394 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001395
1396 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001397 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001398 } else {
1399 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1400 LookupParsedName(R, S, &SS);
1401
1402 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1403 if (!TyD) {
1404 if (R.isAmbiguous()) return true;
1405
John McCallfd225442010-04-09 19:01:14 +00001406 // We don't want access-control diagnostics here.
1407 R.suppressDiagnostics();
1408
Douglas Gregor7a886e12010-01-19 06:46:48 +00001409 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1410 bool NotUnknownSpecialization = false;
1411 DeclContext *DC = computeDeclContext(SS, false);
1412 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1413 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1414
1415 if (!NotUnknownSpecialization) {
1416 // When the scope specifier can refer to a member of an unknown
1417 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001418 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1419 SS.getWithLocInContext(Context),
1420 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001421 if (BaseType.isNull())
1422 return true;
1423
Douglas Gregor7a886e12010-01-19 06:46:48 +00001424 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001425 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001426 }
1427 }
1428
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001429 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001430 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00001431 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001432 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1433 ClassDecl, false, CTC_NoKeywords))) {
1434 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1435 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1436 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001437 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001438 // We have found a non-static data member with a similar
1439 // name to what was typed; complain and initialize that
1440 // member.
1441 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001442 << MemberOrBase << true << CorrectedQuotedStr
1443 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001444 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001445 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001446
1447 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1448 LParenLoc, RParenLoc);
1449 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001450 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001451 const CXXBaseSpecifier *DirectBaseSpec;
1452 const CXXBaseSpecifier *VirtualBaseSpec;
1453 if (FindBaseInitializer(*this, ClassDecl,
1454 Context.getTypeDeclType(Type),
1455 DirectBaseSpec, VirtualBaseSpec)) {
1456 // We have found a direct or virtual base class with a
1457 // similar name to what was typed; complain and initialize
1458 // that base class.
1459 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001460 << MemberOrBase << false << CorrectedQuotedStr
1461 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001462
1463 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1464 : VirtualBaseSpec;
1465 Diag(BaseSpec->getSourceRange().getBegin(),
1466 diag::note_base_class_specified_here)
1467 << BaseSpec->getType()
1468 << BaseSpec->getSourceRange();
1469
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001470 TyD = Type;
1471 }
1472 }
1473 }
1474
Douglas Gregor7a886e12010-01-19 06:46:48 +00001475 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001476 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1477 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1478 return true;
1479 }
John McCall2b194412009-12-21 10:41:20 +00001480 }
1481
Douglas Gregor7a886e12010-01-19 06:46:48 +00001482 if (BaseType.isNull()) {
1483 BaseType = Context.getTypeDeclType(TyD);
1484 if (SS.isSet()) {
1485 NestedNameSpecifier *Qualifier =
1486 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001487
Douglas Gregor7a886e12010-01-19 06:46:48 +00001488 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001489 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001490 }
John McCall2b194412009-12-21 10:41:20 +00001491 }
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
John McCalla93c9342009-12-07 02:54:59 +00001494 if (!TInfo)
1495 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001496
John McCalla93c9342009-12-07 02:54:59 +00001497 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001498 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001499}
1500
Chandler Carruth81c64772011-09-03 01:14:15 +00001501/// Checks a member initializer expression for cases where reference (or
1502/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001503static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1504 Expr *Init,
1505 SourceLocation IdLoc) {
1506 QualType MemberTy = Member->getType();
1507
1508 // We only handle pointers and references currently.
1509 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1510 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1511 return;
1512
1513 const bool IsPointer = MemberTy->isPointerType();
1514 if (IsPointer) {
1515 if (const UnaryOperator *Op
1516 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1517 // The only case we're worried about with pointers requires taking the
1518 // address.
1519 if (Op->getOpcode() != UO_AddrOf)
1520 return;
1521
1522 Init = Op->getSubExpr();
1523 } else {
1524 // We only handle address-of expression initializers for pointers.
1525 return;
1526 }
1527 }
1528
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001529 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1530 // Taking the address of a temporary will be diagnosed as a hard error.
1531 if (IsPointer)
1532 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001533
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001534 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1535 << Member << Init->getSourceRange();
1536 } else if (const DeclRefExpr *DRE
1537 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1538 // We only warn when referring to a non-reference parameter declaration.
1539 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1540 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001541 return;
1542
1543 S.Diag(Init->getExprLoc(),
1544 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1545 : diag::warn_bind_ref_member_to_parameter)
1546 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001547 } else {
1548 // Other initializers are fine.
1549 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001550 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001551
1552 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1553 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00001554}
1555
John McCallb4190042009-11-04 23:02:40 +00001556/// Checks an initializer expression for use of uninitialized fields, such as
1557/// containing the field that is being initialized. Returns true if there is an
1558/// uninitialized field was used an updates the SourceLocation parameter; false
1559/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001560static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001561 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001562 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001563 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1564
Nick Lewycky43ad1822010-06-15 07:32:55 +00001565 if (isa<CallExpr>(S)) {
1566 // Do not descend into function calls or constructors, as the use
1567 // of an uninitialized field may be valid. One would have to inspect
1568 // the contents of the function/ctor to determine if it is safe or not.
1569 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1570 // may be safe, depending on what the function/ctor does.
1571 return false;
1572 }
1573 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1574 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001575
1576 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1577 // The member expression points to a static data member.
1578 assert(VD->isStaticDataMember() &&
1579 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001580 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001581 return false;
1582 }
1583
1584 if (isa<EnumConstantDecl>(RhsField)) {
1585 // The member expression points to an enum.
1586 return false;
1587 }
1588
John McCallb4190042009-11-04 23:02:40 +00001589 if (RhsField == LhsField) {
1590 // Initializing a field with itself. Throw a warning.
1591 // But wait; there are exceptions!
1592 // Exception #1: The field may not belong to this record.
1593 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001594 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001595 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1596 // Even though the field matches, it does not belong to this record.
1597 return false;
1598 }
1599 // None of the exceptions triggered; return true to indicate an
1600 // uninitialized field was used.
1601 *L = ME->getMemberLoc();
1602 return true;
1603 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001604 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001605 // sizeof/alignof doesn't reference contents, do not warn.
1606 return false;
1607 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1608 // address-of doesn't reference contents (the pointer may be dereferenced
1609 // in the same expression but it would be rare; and weird).
1610 if (UOE->getOpcode() == UO_AddrOf)
1611 return false;
John McCallb4190042009-11-04 23:02:40 +00001612 }
John McCall7502c1d2011-02-13 04:07:26 +00001613 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001614 if (!*it) {
1615 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001616 continue;
1617 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001618 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1619 return true;
John McCallb4190042009-11-04 23:02:40 +00001620 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001621 return false;
John McCallb4190042009-11-04 23:02:40 +00001622}
1623
John McCallf312b1e2010-08-26 23:41:50 +00001624MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001625Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001626 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001627 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001628 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001629 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1630 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1631 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001632 "Member must be a FieldDecl or IndirectFieldDecl");
1633
Douglas Gregor464b2f02010-11-05 22:21:31 +00001634 if (Member->isInvalidDecl())
1635 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001636
John McCallb4190042009-11-04 23:02:40 +00001637 // Diagnose value-uses of fields to initialize themselves, e.g.
1638 // foo(foo)
1639 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001640 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001641 for (unsigned i = 0; i < NumArgs; ++i) {
1642 SourceLocation L;
1643 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1644 // FIXME: Return true in the case when other fields are used before being
1645 // uninitialized. For example, let this field be the i'th field. When
1646 // initializing the i'th field, throw a warning if any of the >= i'th
1647 // fields are used, as they are not yet initialized.
1648 // Right now we are only handling the case where the i'th field uses
1649 // itself in its initializer.
1650 Diag(L, diag::warn_field_is_uninit);
1651 }
1652 }
1653
Eli Friedman59c04372009-07-29 19:44:27 +00001654 bool HasDependentArg = false;
1655 for (unsigned i = 0; i < NumArgs; i++)
1656 HasDependentArg |= Args[i]->isTypeDependent();
1657
Chandler Carruth894aed92010-12-06 09:23:57 +00001658 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001659 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001660 // Can't check initialization for a member of dependent type or when
1661 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001662 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001663 RParenLoc,
1664 Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001665
John McCallf85e1932011-06-15 23:02:42 +00001666 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001667 } else {
1668 // Initialize the member.
1669 InitializedEntity MemberEntity =
1670 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1671 : InitializedEntity::InitializeMember(IndirectMember, 0);
1672 InitializationKind Kind =
1673 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001674
Chandler Carruth894aed92010-12-06 09:23:57 +00001675 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1676
1677 ExprResult MemberInit =
1678 InitSeq.Perform(*this, MemberEntity, Kind,
1679 MultiExprArg(*this, Args, NumArgs), 0);
1680 if (MemberInit.isInvalid())
1681 return true;
1682
1683 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1684
1685 // C++0x [class.base.init]p7:
1686 // The initialization of each base and member constitutes a
1687 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001688 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001689 if (MemberInit.isInvalid())
1690 return true;
1691
1692 // If we are in a dependent context, template instantiation will
1693 // perform this type-checking again. Just save the arguments that we
1694 // received in a ParenListExpr.
1695 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1696 // of the information that we have about the member
1697 // initializer. However, deconstructing the ASTs is a dicey process,
1698 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00001699 if (CurContext->isDependentContext()) {
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001700 Init = new (Context) ParenListExpr(
1701 Context, LParenLoc, Args, NumArgs, RParenLoc,
1702 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00001703 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00001704 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00001705 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1706 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001707 }
1708
Chandler Carruth894aed92010-12-06 09:23:57 +00001709 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001710 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001711 IdLoc, LParenLoc, Init,
1712 RParenLoc);
1713 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001714 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001715 IdLoc, LParenLoc, Init,
1716 RParenLoc);
1717 }
Eli Friedman59c04372009-07-29 19:44:27 +00001718}
1719
John McCallf312b1e2010-08-26 23:41:50 +00001720MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001721Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1722 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001723 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001724 SourceLocation LParenLoc,
1725 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001726 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001727 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1728 if (!LangOpts.CPlusPlus0x)
1729 return Diag(Loc, diag::err_delegation_0x_only)
1730 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001731
Sean Hunt41717662011-02-26 19:13:13 +00001732 // Initialize the object.
1733 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1734 QualType(ClassDecl->getTypeForDecl(), 0));
1735 InitializationKind Kind =
1736 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1737
1738 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1739
1740 ExprResult DelegationInit =
1741 InitSeq.Perform(*this, DelegationEntity, Kind,
1742 MultiExprArg(*this, Args, NumArgs), 0);
1743 if (DelegationInit.isInvalid())
1744 return true;
1745
1746 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001747 CXXConstructorDecl *Constructor
1748 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001749 assert(Constructor && "Delegating constructor with no target?");
1750
1751 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1752
1753 // C++0x [class.base.init]p7:
1754 // The initialization of each base and member constitutes a
1755 // full-expression.
1756 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1757 if (DelegationInit.isInvalid())
1758 return true;
1759
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001760 assert(!CurContext->isDependentContext());
Sean Hunt41717662011-02-26 19:13:13 +00001761 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1762 DelegationInit.takeAs<Expr>(),
1763 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001764}
1765
1766MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001767Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001768 Expr **Args, unsigned NumArgs,
1769 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001770 CXXRecordDecl *ClassDecl,
1771 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001772 bool HasDependentArg = false;
1773 for (unsigned i = 0; i < NumArgs; i++)
1774 HasDependentArg |= Args[i]->isTypeDependent();
1775
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001776 SourceLocation BaseLoc
1777 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1778
1779 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1780 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1781 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1782
1783 // C++ [class.base.init]p2:
1784 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001785 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001786 // of that class, the mem-initializer is ill-formed. A
1787 // mem-initializer-list can initialize a base class using any
1788 // name that denotes that base class type.
1789 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1790
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001791 if (EllipsisLoc.isValid()) {
1792 // This is a pack expansion.
1793 if (!BaseType->containsUnexpandedParameterPack()) {
1794 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1795 << SourceRange(BaseLoc, RParenLoc);
1796
1797 EllipsisLoc = SourceLocation();
1798 }
1799 } else {
1800 // Check for any unexpanded parameter packs.
1801 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1802 return true;
1803
1804 for (unsigned I = 0; I != NumArgs; ++I)
1805 if (DiagnoseUnexpandedParameterPack(Args[I]))
1806 return true;
1807 }
1808
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001809 // Check for direct and virtual base classes.
1810 const CXXBaseSpecifier *DirectBaseSpec = 0;
1811 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1812 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001813 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1814 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001815 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1816 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001817
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001818 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1819 VirtualBaseSpec);
1820
1821 // C++ [base.class.init]p2:
1822 // Unless the mem-initializer-id names a nonstatic data member of the
1823 // constructor's class or a direct or virtual base of that class, the
1824 // mem-initializer is ill-formed.
1825 if (!DirectBaseSpec && !VirtualBaseSpec) {
1826 // If the class has any dependent bases, then it's possible that
1827 // one of those types will resolve to the same type as
1828 // BaseType. Therefore, just treat this as a dependent base
1829 // class initialization. FIXME: Should we try to check the
1830 // initialization anyway? It seems odd.
1831 if (ClassDecl->hasAnyDependentBases())
1832 Dependent = true;
1833 else
1834 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1835 << BaseType << Context.getTypeDeclType(ClassDecl)
1836 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1837 }
1838 }
1839
1840 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001841 // Can't check initialization for a base of dependent type or when
1842 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001843 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001844 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001845 RParenLoc, BaseType));
Eli Friedman59c04372009-07-29 19:44:27 +00001846
John McCallf85e1932011-06-15 23:02:42 +00001847 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Sean Huntcbb67482011-01-08 20:30:50 +00001849 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001850 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001851 LParenLoc,
1852 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001853 RParenLoc,
1854 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001855 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001856
1857 // C++ [base.class.init]p2:
1858 // If a mem-initializer-id is ambiguous because it designates both
1859 // a direct non-virtual base class and an inherited virtual base
1860 // class, the mem-initializer is ill-formed.
1861 if (DirectBaseSpec && VirtualBaseSpec)
1862 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001863 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001864
1865 CXXBaseSpecifier *BaseSpec
1866 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1867 if (!BaseSpec)
1868 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1869
1870 // Initialize the base.
1871 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001872 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001873 InitializationKind Kind =
1874 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1875
1876 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1877
John McCall60d7b3a2010-08-24 06:29:42 +00001878 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001879 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001880 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001881 if (BaseInit.isInvalid())
1882 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001883
1884 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001885
1886 // C++0x [class.base.init]p7:
1887 // The initialization of each base and member constitutes a
1888 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001889 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001890 if (BaseInit.isInvalid())
1891 return true;
1892
1893 // If we are in a dependent context, template instantiation will
1894 // perform this type-checking again. Just save the arguments that we
1895 // received in a ParenListExpr.
1896 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1897 // of the information that we have about the base
1898 // initializer. However, deconstructing the ASTs is a dicey process,
1899 // and this approach is far more likely to get the corner cases right.
1900 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001901 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001902 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001903 RParenLoc, BaseType));
Sean Huntcbb67482011-01-08 20:30:50 +00001904 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001905 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001906 LParenLoc,
1907 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001908 RParenLoc,
1909 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001910 }
1911
Sean Huntcbb67482011-01-08 20:30:50 +00001912 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001913 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001914 LParenLoc,
1915 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001916 RParenLoc,
1917 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001918}
1919
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001920// Create a static_cast\<T&&>(expr).
1921static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1922 QualType ExprType = E->getType();
1923 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1924 SourceLocation ExprLoc = E->getLocStart();
1925 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1926 TargetType, ExprLoc);
1927
1928 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1929 SourceRange(ExprLoc, ExprLoc),
1930 E->getSourceRange()).take();
1931}
1932
Anders Carlssone5ef7402010-04-23 03:10:23 +00001933/// ImplicitInitializerKind - How an implicit base or member initializer should
1934/// initialize its base or member.
1935enum ImplicitInitializerKind {
1936 IIK_Default,
1937 IIK_Copy,
1938 IIK_Move
1939};
1940
Anders Carlssondefefd22010-04-23 02:00:02 +00001941static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001942BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001943 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001944 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001945 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001946 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001947 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001948 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1949 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001950
John McCall60d7b3a2010-08-24 06:29:42 +00001951 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001952
1953 switch (ImplicitInitKind) {
1954 case IIK_Default: {
1955 InitializationKind InitKind
1956 = InitializationKind::CreateDefault(Constructor->getLocation());
1957 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1958 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001959 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001960 break;
1961 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001962
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001963 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00001964 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001965 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001966 ParmVarDecl *Param = Constructor->getParamDecl(0);
1967 QualType ParamType = Param->getType().getNonReferenceType();
1968
1969 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001970 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001971 Constructor->getLocation(), ParamType,
1972 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001973
Anders Carlssonc7957502010-04-24 22:02:54 +00001974 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001975 QualType ArgTy =
1976 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1977 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001978
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001979 if (Moving) {
1980 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1981 }
1982
John McCallf871d0c2010-08-07 06:22:56 +00001983 CXXCastPath BasePath;
1984 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001985 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1986 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00001987 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001988 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001989
Anders Carlssone5ef7402010-04-23 03:10:23 +00001990 InitializationKind InitKind
1991 = InitializationKind::CreateDirect(Constructor->getLocation(),
1992 SourceLocation(), SourceLocation());
1993 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1994 &CopyCtorArg, 1);
1995 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001996 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001997 break;
1998 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00001999 }
John McCall9ae2f072010-08-23 23:25:46 +00002000
Douglas Gregor53c374f2010-12-07 00:41:46 +00002001 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002002 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002003 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002004
Anders Carlssondefefd22010-04-23 02:00:02 +00002005 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002006 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002007 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2008 SourceLocation()),
2009 BaseSpec->isVirtual(),
2010 SourceLocation(),
2011 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002012 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002013 SourceLocation());
2014
Anders Carlssondefefd22010-04-23 02:00:02 +00002015 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002016}
2017
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002018static bool RefersToRValueRef(Expr *MemRef) {
2019 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2020 return Referenced->getType()->isRValueReferenceType();
2021}
2022
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002023static bool
2024BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002025 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002026 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002027 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002028 if (Field->isInvalidDecl())
2029 return true;
2030
Chandler Carruthf186b542010-06-29 23:50:44 +00002031 SourceLocation Loc = Constructor->getLocation();
2032
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002033 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2034 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002035 ParmVarDecl *Param = Constructor->getParamDecl(0);
2036 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002037
2038 // Suppress copying zero-width bitfields.
2039 if (const Expr *Width = Field->getBitWidth())
2040 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2041 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002042
2043 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002044 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002045 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002046
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002047 if (Moving) {
2048 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2049 }
2050
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002051 // Build a reference to this field within the parameter.
2052 CXXScopeSpec SS;
2053 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2054 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002055 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2056 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002057 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002058 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002059 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002060 ParamType, Loc,
2061 /*IsArrow=*/false,
2062 SS,
2063 /*FirstQualifierInScope=*/0,
2064 MemberLookup,
2065 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002066 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002067 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002068
2069 // C++11 [class.copy]p15:
2070 // - if a member m has rvalue reference type T&&, it is direct-initialized
2071 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002072 if (RefersToRValueRef(CtorArg.get())) {
2073 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002074 }
2075
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002076 // When the field we are copying is an array, create index variables for
2077 // each dimension of the array. We use these index variables to subscript
2078 // the source array, and other clients (e.g., CodeGen) will perform the
2079 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002080 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002081 QualType BaseType = Field->getType();
2082 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002083 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002084 while (const ConstantArrayType *Array
2085 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002086 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002087 // Create the iteration variable for this array index.
2088 IdentifierInfo *IterationVarName = 0;
2089 {
2090 llvm::SmallString<8> Str;
2091 llvm::raw_svector_ostream OS(Str);
2092 OS << "__i" << IndexVariables.size();
2093 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2094 }
2095 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002096 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002097 IterationVarName, SizeType,
2098 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002099 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002100 IndexVariables.push_back(IterationVar);
2101
2102 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002103 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002104 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002105 assert(!IterationVarRef.isInvalid() &&
2106 "Reference to invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002107
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002108 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002109 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002110 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002111 Loc);
2112 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002113 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002114
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002115 BaseType = Array->getElementType();
2116 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002117
2118 // The array subscript expression is an lvalue, which is wrong for moving.
2119 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002120 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002121
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002122 // Construct the entity that we will be initializing. For an array, this
2123 // will be first element in the array, which may require several levels
2124 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002125 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002126 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002127 if (Indirect)
2128 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2129 else
2130 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002131 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2132 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2133 0,
2134 Entities.back()));
2135
2136 // Direct-initialize to use the copy constructor.
2137 InitializationKind InitKind =
2138 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2139
Sebastian Redl74e611a2011-09-04 18:14:28 +00002140 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002141 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002142 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002143
John McCall60d7b3a2010-08-24 06:29:42 +00002144 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002145 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002146 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002147 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002148 if (MemberInit.isInvalid())
2149 return true;
2150
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002151 if (Indirect) {
2152 assert(IndexVariables.size() == 0 &&
2153 "Indirect field improperly initialized");
2154 CXXMemberInit
2155 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2156 Loc, Loc,
2157 MemberInit.takeAs<Expr>(),
2158 Loc);
2159 } else
2160 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2161 Loc, MemberInit.takeAs<Expr>(),
2162 Loc,
2163 IndexVariables.data(),
2164 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002165 return false;
2166 }
2167
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002168 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2169
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002170 QualType FieldBaseElementType =
2171 SemaRef.Context.getBaseElementType(Field->getType());
2172
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002173 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002174 InitializedEntity InitEntity
2175 = Indirect? InitializedEntity::InitializeMember(Indirect)
2176 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002177 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002178 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002179
2180 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002181 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002182 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002183
Douglas Gregor53c374f2010-12-07 00:41:46 +00002184 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002185 if (MemberInit.isInvalid())
2186 return true;
2187
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002188 if (Indirect)
2189 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2190 Indirect, Loc,
2191 Loc,
2192 MemberInit.get(),
2193 Loc);
2194 else
2195 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2196 Field, Loc, Loc,
2197 MemberInit.get(),
2198 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002199 return false;
2200 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002201
Sean Hunt1f2f3842011-05-17 00:19:05 +00002202 if (!Field->getParent()->isUnion()) {
2203 if (FieldBaseElementType->isReferenceType()) {
2204 SemaRef.Diag(Constructor->getLocation(),
2205 diag::err_uninitialized_member_in_ctor)
2206 << (int)Constructor->isImplicit()
2207 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2208 << 0 << Field->getDeclName();
2209 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2210 return true;
2211 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002212
Sean Hunt1f2f3842011-05-17 00:19:05 +00002213 if (FieldBaseElementType.isConstQualified()) {
2214 SemaRef.Diag(Constructor->getLocation(),
2215 diag::err_uninitialized_member_in_ctor)
2216 << (int)Constructor->isImplicit()
2217 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2218 << 1 << Field->getDeclName();
2219 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2220 return true;
2221 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002222 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002223
John McCallf85e1932011-06-15 23:02:42 +00002224 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2225 FieldBaseElementType->isObjCRetainableType() &&
2226 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2227 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2228 // Instant objects:
2229 // Default-initialize Objective-C pointers to NULL.
2230 CXXMemberInit
2231 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2232 Loc, Loc,
2233 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2234 Loc);
2235 return false;
2236 }
2237
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002238 // Nothing to initialize.
2239 CXXMemberInit = 0;
2240 return false;
2241}
John McCallf1860e52010-05-20 23:23:51 +00002242
2243namespace {
2244struct BaseAndFieldInfo {
2245 Sema &S;
2246 CXXConstructorDecl *Ctor;
2247 bool AnyErrorsInInits;
2248 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002249 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002250 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002251
2252 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2253 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002254 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2255 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002256 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002257 else if (Generated && Ctor->isMoveConstructor())
2258 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002259 else
2260 IIK = IIK_Default;
2261 }
2262};
2263}
2264
Richard Smith7a614d82011-06-11 17:19:42 +00002265static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002266 FieldDecl *Field,
2267 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002268
Chandler Carruthe861c602010-06-30 02:59:29 +00002269 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002270 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002271 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002272 return false;
2273 }
2274
Richard Smith7a614d82011-06-11 17:19:42 +00002275 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2276 // has a brace-or-equal-initializer, the entity is initialized as specified
2277 // in [dcl.init].
2278 if (Field->hasInClassInitializer()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002279 CXXCtorInitializer *Init;
2280 if (Indirect)
2281 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2282 SourceLocation(),
2283 SourceLocation(), 0,
2284 SourceLocation());
2285 else
2286 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2287 SourceLocation(),
2288 SourceLocation(), 0,
2289 SourceLocation());
2290 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002291 return false;
2292 }
2293
John McCallf1860e52010-05-20 23:23:51 +00002294 // Don't try to build an implicit initializer if there were semantic
2295 // errors in any of the initializers (and therefore we might be
2296 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002297 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002298 return false;
2299
Sean Huntcbb67482011-01-08 20:30:50 +00002300 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002301 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2302 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002303 return true;
John McCallf1860e52010-05-20 23:23:51 +00002304
Francois Pichet00eb3f92010-12-04 09:14:42 +00002305 if (Init)
2306 Info.AllToInit.push_back(Init);
2307
John McCallf1860e52010-05-20 23:23:51 +00002308 return false;
2309}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002310
2311bool
2312Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2313 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002314 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002315 Constructor->setNumCtorInitializers(1);
2316 CXXCtorInitializer **initializer =
2317 new (Context) CXXCtorInitializer*[1];
2318 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2319 Constructor->setCtorInitializers(initializer);
2320
Sean Huntb76af9c2011-05-03 23:05:34 +00002321 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2322 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2323 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2324 }
2325
Sean Huntc1598702011-05-05 00:05:47 +00002326 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002327
Sean Hunt059ce0d2011-05-01 07:04:31 +00002328 return false;
2329}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002330
2331/// \brief Determine whether the given indirect field declaration is somewhere
2332/// within an anonymous union.
2333static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2334 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2335 CEnd = F->chain_end();
2336 C != CEnd; ++C)
2337 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2338 if (Record->isUnion())
2339 return true;
2340
2341 return false;
2342}
2343
John McCallb77115d2011-06-17 00:18:42 +00002344bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2345 CXXCtorInitializer **Initializers,
2346 unsigned NumInitializers,
2347 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002348 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002349 // Just store the initializers as written, they will be checked during
2350 // instantiation.
2351 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002352 Constructor->setNumCtorInitializers(NumInitializers);
2353 CXXCtorInitializer **baseOrMemberInitializers =
2354 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002355 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002356 NumInitializers * sizeof(CXXCtorInitializer*));
2357 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002358 }
2359
2360 return false;
2361 }
2362
John McCallf1860e52010-05-20 23:23:51 +00002363 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002364
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002365 // We need to build the initializer AST according to order of construction
2366 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002367 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002368 if (!ClassDecl)
2369 return true;
2370
Eli Friedman80c30da2009-11-09 19:20:36 +00002371 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002373 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002374 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002375
2376 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002377 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002378 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002379 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002380 }
2381
Anders Carlsson711f34a2010-04-21 19:52:01 +00002382 // Keep track of the direct virtual bases.
2383 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2384 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2385 E = ClassDecl->bases_end(); I != E; ++I) {
2386 if (I->isVirtual())
2387 DirectVBases.insert(I);
2388 }
2389
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002390 // Push virtual bases before others.
2391 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2392 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2393
Sean Huntcbb67482011-01-08 20:30:50 +00002394 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002395 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2396 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002397 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002398 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002399 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002400 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002401 VBase, IsInheritedVirtualBase,
2402 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002403 HadError = true;
2404 continue;
2405 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002406
John McCallf1860e52010-05-20 23:23:51 +00002407 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002408 }
2409 }
Mike Stump1eb44332009-09-09 15:08:12 +00002410
John McCallf1860e52010-05-20 23:23:51 +00002411 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002412 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2413 E = ClassDecl->bases_end(); Base != E; ++Base) {
2414 // Virtuals are in the virtual base list and already constructed.
2415 if (Base->isVirtual())
2416 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Sean Huntcbb67482011-01-08 20:30:50 +00002418 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002419 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2420 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002421 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002422 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002423 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002424 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002425 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002426 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002427 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002428 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002429
John McCallf1860e52010-05-20 23:23:51 +00002430 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002431 }
2432 }
Mike Stump1eb44332009-09-09 15:08:12 +00002433
John McCallf1860e52010-05-20 23:23:51 +00002434 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002435 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2436 MemEnd = ClassDecl->decls_end();
2437 Mem != MemEnd; ++Mem) {
2438 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2439 if (F->getType()->isIncompleteArrayType()) {
2440 assert(ClassDecl->hasFlexibleArrayMember() &&
2441 "Incomplete array type is not valid");
2442 continue;
2443 }
2444
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002445 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002446 // handle anonymous struct/union fields based on their individual
2447 // indirect fields.
2448 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2449 continue;
2450
2451 if (CollectFieldInitializer(*this, Info, F))
2452 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002453 continue;
2454 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002455
2456 // Beyond this point, we only consider default initialization.
2457 if (Info.IIK != IIK_Default)
2458 continue;
2459
2460 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2461 if (F->getType()->isIncompleteArrayType()) {
2462 assert(ClassDecl->hasFlexibleArrayMember() &&
2463 "Incomplete array type is not valid");
2464 continue;
2465 }
2466
2467 // If this field is somewhere within an anonymous union, we only
2468 // initialize it if there's an explicit initializer.
2469 if (isWithinAnonymousUnion(F)) {
2470 if (CXXCtorInitializer *Init
2471 = Info.AllBaseFields.lookup(F->getAnonField())) {
2472 Info.AllToInit.push_back(Init);
2473 }
2474
2475 continue;
2476 }
2477
2478 // Initialize each field of an anonymous struct individually.
2479 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2480 HadError = true;
2481
2482 continue;
2483 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002484 }
Mike Stump1eb44332009-09-09 15:08:12 +00002485
John McCallf1860e52010-05-20 23:23:51 +00002486 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002487 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002488 Constructor->setNumCtorInitializers(NumInitializers);
2489 CXXCtorInitializer **baseOrMemberInitializers =
2490 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002491 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002492 NumInitializers * sizeof(CXXCtorInitializer*));
2493 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002494
John McCallef027fe2010-03-16 21:39:52 +00002495 // Constructors implicitly reference the base and member
2496 // destructors.
2497 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2498 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002499 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002500
2501 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002502}
2503
Eli Friedman6347f422009-07-21 19:28:10 +00002504static void *GetKeyForTopLevelField(FieldDecl *Field) {
2505 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002506 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002507 if (RT->getDecl()->isAnonymousStructOrUnion())
2508 return static_cast<void *>(RT->getDecl());
2509 }
2510 return static_cast<void *>(Field);
2511}
2512
Anders Carlssonea356fb2010-04-02 05:42:15 +00002513static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002514 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002515}
2516
Anders Carlssonea356fb2010-04-02 05:42:15 +00002517static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002518 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002519 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002520 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002521
Eli Friedman6347f422009-07-21 19:28:10 +00002522 // For fields injected into the class via declaration of an anonymous union,
2523 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002524 FieldDecl *Field = Member->getAnyMember();
2525
John McCall3c3ccdb2010-04-10 09:28:51 +00002526 // If the field is a member of an anonymous struct or union, our key
2527 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002528 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002529 if (RD->isAnonymousStructOrUnion()) {
2530 while (true) {
2531 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2532 if (Parent->isAnonymousStructOrUnion())
2533 RD = Parent;
2534 else
2535 break;
2536 }
2537
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002538 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002539 }
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002541 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002542}
2543
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002544static void
2545DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002546 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002547 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002548 unsigned NumInits) {
2549 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002550 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002552 // Don't check initializers order unless the warning is enabled at the
2553 // location of at least one initializer.
2554 bool ShouldCheckOrder = false;
2555 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002556 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002557 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2558 Init->getSourceLocation())
2559 != Diagnostic::Ignored) {
2560 ShouldCheckOrder = true;
2561 break;
2562 }
2563 }
2564 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002565 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002566
John McCalld6ca8da2010-04-10 07:37:23 +00002567 // Build the list of bases and members in the order that they'll
2568 // actually be initialized. The explicit initializers should be in
2569 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002570 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Anders Carlsson071d6102010-04-02 03:38:04 +00002572 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2573
John McCalld6ca8da2010-04-10 07:37:23 +00002574 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002575 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002576 ClassDecl->vbases_begin(),
2577 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002578 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002579
John McCalld6ca8da2010-04-10 07:37:23 +00002580 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002581 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002582 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002583 if (Base->isVirtual())
2584 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002585 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002586 }
Mike Stump1eb44332009-09-09 15:08:12 +00002587
John McCalld6ca8da2010-04-10 07:37:23 +00002588 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002589 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2590 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002591 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002592
John McCalld6ca8da2010-04-10 07:37:23 +00002593 unsigned NumIdealInits = IdealInitKeys.size();
2594 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002595
Sean Huntcbb67482011-01-08 20:30:50 +00002596 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002597 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002598 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002599 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002600
2601 // Scan forward to try to find this initializer in the idealized
2602 // initializers list.
2603 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2604 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002605 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002606
2607 // If we didn't find this initializer, it must be because we
2608 // scanned past it on a previous iteration. That can only
2609 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002610 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002611 Sema::SemaDiagnosticBuilder D =
2612 SemaRef.Diag(PrevInit->getSourceLocation(),
2613 diag::warn_initializer_out_of_order);
2614
Francois Pichet00eb3f92010-12-04 09:14:42 +00002615 if (PrevInit->isAnyMemberInitializer())
2616 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002617 else
2618 D << 1 << PrevInit->getBaseClassInfo()->getType();
2619
Francois Pichet00eb3f92010-12-04 09:14:42 +00002620 if (Init->isAnyMemberInitializer())
2621 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002622 else
2623 D << 1 << Init->getBaseClassInfo()->getType();
2624
2625 // Move back to the initializer's location in the ideal list.
2626 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2627 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002628 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002629
2630 assert(IdealIndex != NumIdealInits &&
2631 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002632 }
John McCalld6ca8da2010-04-10 07:37:23 +00002633
2634 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002635 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002636}
2637
John McCall3c3ccdb2010-04-10 09:28:51 +00002638namespace {
2639bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002640 CXXCtorInitializer *Init,
2641 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002642 if (!PrevInit) {
2643 PrevInit = Init;
2644 return false;
2645 }
2646
2647 if (FieldDecl *Field = Init->getMember())
2648 S.Diag(Init->getSourceLocation(),
2649 diag::err_multiple_mem_initialization)
2650 << Field->getDeclName()
2651 << Init->getSourceRange();
2652 else {
John McCallf4c73712011-01-19 06:33:43 +00002653 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002654 assert(BaseClass && "neither field nor base");
2655 S.Diag(Init->getSourceLocation(),
2656 diag::err_multiple_base_initialization)
2657 << QualType(BaseClass, 0)
2658 << Init->getSourceRange();
2659 }
2660 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2661 << 0 << PrevInit->getSourceRange();
2662
2663 return true;
2664}
2665
Sean Huntcbb67482011-01-08 20:30:50 +00002666typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002667typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2668
2669bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002670 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002671 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002672 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002673 RecordDecl *Parent = Field->getParent();
2674 if (!Parent->isAnonymousStructOrUnion())
2675 return false;
2676
2677 NamedDecl *Child = Field;
2678 do {
2679 if (Parent->isUnion()) {
2680 UnionEntry &En = Unions[Parent];
2681 if (En.first && En.first != Child) {
2682 S.Diag(Init->getSourceLocation(),
2683 diag::err_multiple_mem_union_initialization)
2684 << Field->getDeclName()
2685 << Init->getSourceRange();
2686 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2687 << 0 << En.second->getSourceRange();
2688 return true;
2689 } else if (!En.first) {
2690 En.first = Child;
2691 En.second = Init;
2692 }
2693 }
2694
2695 Child = Parent;
2696 Parent = cast<RecordDecl>(Parent->getDeclContext());
2697 } while (Parent->isAnonymousStructOrUnion());
2698
2699 return false;
2700}
2701}
2702
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002703/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002704void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002705 SourceLocation ColonLoc,
2706 MemInitTy **meminits, unsigned NumMemInits,
2707 bool AnyErrors) {
2708 if (!ConstructorDecl)
2709 return;
2710
2711 AdjustDeclIfTemplate(ConstructorDecl);
2712
2713 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002714 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002715
2716 if (!Constructor) {
2717 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2718 return;
2719 }
2720
Sean Huntcbb67482011-01-08 20:30:50 +00002721 CXXCtorInitializer **MemInits =
2722 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002723
2724 // Mapping for the duplicate initializers check.
2725 // For member initializers, this is keyed with a FieldDecl*.
2726 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002727 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002728
2729 // Mapping for the inconsistent anonymous-union initializers check.
2730 RedundantUnionMap MemberUnions;
2731
Anders Carlssonea356fb2010-04-02 05:42:15 +00002732 bool HadError = false;
2733 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002734 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002735
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002736 // Set the source order index.
2737 Init->setSourceOrder(i);
2738
Francois Pichet00eb3f92010-12-04 09:14:42 +00002739 if (Init->isAnyMemberInitializer()) {
2740 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002741 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2742 CheckRedundantUnionInit(*this, Init, MemberUnions))
2743 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002744 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002745 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2746 if (CheckRedundantInit(*this, Init, Members[Key]))
2747 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002748 } else {
2749 assert(Init->isDelegatingInitializer());
2750 // This must be the only initializer
2751 if (i != 0 || NumMemInits > 1) {
2752 Diag(MemInits[0]->getSourceLocation(),
2753 diag::err_delegating_initializer_alone)
2754 << MemInits[0]->getSourceRange();
2755 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002756 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002757 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002758 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002759 // Return immediately as the initializer is set.
2760 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002761 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002762 }
2763
Anders Carlssonea356fb2010-04-02 05:42:15 +00002764 if (HadError)
2765 return;
2766
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002767 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002768
Sean Huntcbb67482011-01-08 20:30:50 +00002769 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002770}
2771
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002772void
John McCallef027fe2010-03-16 21:39:52 +00002773Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2774 CXXRecordDecl *ClassDecl) {
2775 // Ignore dependent contexts.
2776 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002777 return;
John McCall58e6f342010-03-16 05:22:47 +00002778
2779 // FIXME: all the access-control diagnostics are positioned on the
2780 // field/base declaration. That's probably good; that said, the
2781 // user might reasonably want to know why the destructor is being
2782 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002783
Anders Carlsson9f853df2009-11-17 04:44:12 +00002784 // Non-static data members.
2785 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2786 E = ClassDecl->field_end(); I != E; ++I) {
2787 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002788 if (Field->isInvalidDecl())
2789 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002790 QualType FieldType = Context.getBaseElementType(Field->getType());
2791
2792 const RecordType* RT = FieldType->getAs<RecordType>();
2793 if (!RT)
2794 continue;
2795
2796 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002797 if (FieldClassDecl->isInvalidDecl())
2798 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002799 if (FieldClassDecl->hasTrivialDestructor())
2800 continue;
2801
Douglas Gregordb89f282010-07-01 22:47:18 +00002802 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002803 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002804 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002805 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002806 << Field->getDeclName()
2807 << FieldType);
2808
John McCallef027fe2010-03-16 21:39:52 +00002809 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002810 }
2811
John McCall58e6f342010-03-16 05:22:47 +00002812 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2813
Anders Carlsson9f853df2009-11-17 04:44:12 +00002814 // Bases.
2815 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2816 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002817 // Bases are always records in a well-formed non-dependent class.
2818 const RecordType *RT = Base->getType()->getAs<RecordType>();
2819
2820 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002821 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002822 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002823
John McCall58e6f342010-03-16 05:22:47 +00002824 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002825 // If our base class is invalid, we probably can't get its dtor anyway.
2826 if (BaseClassDecl->isInvalidDecl())
2827 continue;
2828 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002829 if (BaseClassDecl->hasTrivialDestructor())
2830 continue;
John McCall58e6f342010-03-16 05:22:47 +00002831
Douglas Gregordb89f282010-07-01 22:47:18 +00002832 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002833 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002834
2835 // FIXME: caret should be on the start of the class name
2836 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002837 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002838 << Base->getType()
2839 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002840
John McCallef027fe2010-03-16 21:39:52 +00002841 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002842 }
2843
2844 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002845 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2846 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002847
2848 // Bases are always records in a well-formed non-dependent class.
2849 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2850
2851 // Ignore direct virtual bases.
2852 if (DirectVirtualBases.count(RT))
2853 continue;
2854
John McCall58e6f342010-03-16 05:22:47 +00002855 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002856 // If our base class is invalid, we probably can't get its dtor anyway.
2857 if (BaseClassDecl->isInvalidDecl())
2858 continue;
2859 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002860 if (BaseClassDecl->hasTrivialDestructor())
2861 continue;
John McCall58e6f342010-03-16 05:22:47 +00002862
Douglas Gregordb89f282010-07-01 22:47:18 +00002863 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002864 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002865 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002866 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002867 << VBase->getType());
2868
John McCallef027fe2010-03-16 21:39:52 +00002869 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002870 }
2871}
2872
John McCalld226f652010-08-21 09:40:31 +00002873void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002874 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002875 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Mike Stump1eb44332009-09-09 15:08:12 +00002877 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002878 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002879 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002880}
2881
Mike Stump1eb44332009-09-09 15:08:12 +00002882bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002883 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002884 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002885 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002886 else
John McCall94c3b562010-08-18 09:41:07 +00002887 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002888}
2889
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002890bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002891 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002892 if (!getLangOptions().CPlusPlus)
2893 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002894
Anders Carlsson11f21a02009-03-23 19:10:31 +00002895 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002896 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Ted Kremenek6217b802009-07-29 21:53:49 +00002898 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002899 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002900 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002901 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002902
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002903 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002904 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002905 }
Mike Stump1eb44332009-09-09 15:08:12 +00002906
Ted Kremenek6217b802009-07-29 21:53:49 +00002907 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002908 if (!RT)
2909 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002910
John McCall86ff3082010-02-04 22:26:26 +00002911 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002912
John McCall94c3b562010-08-18 09:41:07 +00002913 // We can't answer whether something is abstract until it has a
2914 // definition. If it's currently being defined, we'll walk back
2915 // over all the declarations when we have a full definition.
2916 const CXXRecordDecl *Def = RD->getDefinition();
2917 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002918 return false;
2919
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002920 if (!RD->isAbstract())
2921 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002922
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002923 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002924 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002925
John McCall94c3b562010-08-18 09:41:07 +00002926 return true;
2927}
2928
2929void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2930 // Check if we've already emitted the list of pure virtual functions
2931 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002932 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002933 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002935 CXXFinalOverriderMap FinalOverriders;
2936 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002938 // Keep a set of seen pure methods so we won't diagnose the same method
2939 // more than once.
2940 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2941
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002942 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2943 MEnd = FinalOverriders.end();
2944 M != MEnd;
2945 ++M) {
2946 for (OverridingMethods::iterator SO = M->second.begin(),
2947 SOEnd = M->second.end();
2948 SO != SOEnd; ++SO) {
2949 // C++ [class.abstract]p4:
2950 // A class is abstract if it contains or inherits at least one
2951 // pure virtual function for which the final overrider is pure
2952 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002954 //
2955 if (SO->second.size() != 1)
2956 continue;
2957
2958 if (!SO->second.front().Method->isPure())
2959 continue;
2960
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002961 if (!SeenPureMethods.insert(SO->second.front().Method))
2962 continue;
2963
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002964 Diag(SO->second.front().Method->getLocation(),
2965 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002966 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002967 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002968 }
2969
2970 if (!PureVirtualClassDiagSet)
2971 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2972 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002973}
2974
Anders Carlsson8211eff2009-03-24 01:19:16 +00002975namespace {
John McCall94c3b562010-08-18 09:41:07 +00002976struct AbstractUsageInfo {
2977 Sema &S;
2978 CXXRecordDecl *Record;
2979 CanQualType AbstractType;
2980 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002981
John McCall94c3b562010-08-18 09:41:07 +00002982 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2983 : S(S), Record(Record),
2984 AbstractType(S.Context.getCanonicalType(
2985 S.Context.getTypeDeclType(Record))),
2986 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002987
John McCall94c3b562010-08-18 09:41:07 +00002988 void DiagnoseAbstractType() {
2989 if (Invalid) return;
2990 S.DiagnoseAbstractType(Record);
2991 Invalid = true;
2992 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002993
John McCall94c3b562010-08-18 09:41:07 +00002994 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2995};
2996
2997struct CheckAbstractUsage {
2998 AbstractUsageInfo &Info;
2999 const NamedDecl *Ctx;
3000
3001 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3002 : Info(Info), Ctx(Ctx) {}
3003
3004 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3005 switch (TL.getTypeLocClass()) {
3006#define ABSTRACT_TYPELOC(CLASS, PARENT)
3007#define TYPELOC(CLASS, PARENT) \
3008 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3009#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003010 }
John McCall94c3b562010-08-18 09:41:07 +00003011 }
Mike Stump1eb44332009-09-09 15:08:12 +00003012
John McCall94c3b562010-08-18 09:41:07 +00003013 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3014 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3015 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003016 if (!TL.getArg(I))
3017 continue;
3018
John McCall94c3b562010-08-18 09:41:07 +00003019 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3020 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003021 }
John McCall94c3b562010-08-18 09:41:07 +00003022 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003023
John McCall94c3b562010-08-18 09:41:07 +00003024 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3025 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3026 }
Mike Stump1eb44332009-09-09 15:08:12 +00003027
John McCall94c3b562010-08-18 09:41:07 +00003028 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3029 // Visit the type parameters from a permissive context.
3030 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3031 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3032 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3033 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3034 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3035 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003036 }
John McCall94c3b562010-08-18 09:41:07 +00003037 }
Mike Stump1eb44332009-09-09 15:08:12 +00003038
John McCall94c3b562010-08-18 09:41:07 +00003039 // Visit pointee types from a permissive context.
3040#define CheckPolymorphic(Type) \
3041 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3042 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3043 }
3044 CheckPolymorphic(PointerTypeLoc)
3045 CheckPolymorphic(ReferenceTypeLoc)
3046 CheckPolymorphic(MemberPointerTypeLoc)
3047 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003048
John McCall94c3b562010-08-18 09:41:07 +00003049 /// Handle all the types we haven't given a more specific
3050 /// implementation for above.
3051 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3052 // Every other kind of type that we haven't called out already
3053 // that has an inner type is either (1) sugar or (2) contains that
3054 // inner type in some way as a subobject.
3055 if (TypeLoc Next = TL.getNextTypeLoc())
3056 return Visit(Next, Sel);
3057
3058 // If there's no inner type and we're in a permissive context,
3059 // don't diagnose.
3060 if (Sel == Sema::AbstractNone) return;
3061
3062 // Check whether the type matches the abstract type.
3063 QualType T = TL.getType();
3064 if (T->isArrayType()) {
3065 Sel = Sema::AbstractArrayType;
3066 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003067 }
John McCall94c3b562010-08-18 09:41:07 +00003068 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3069 if (CT != Info.AbstractType) return;
3070
3071 // It matched; do some magic.
3072 if (Sel == Sema::AbstractArrayType) {
3073 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3074 << T << TL.getSourceRange();
3075 } else {
3076 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3077 << Sel << T << TL.getSourceRange();
3078 }
3079 Info.DiagnoseAbstractType();
3080 }
3081};
3082
3083void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3084 Sema::AbstractDiagSelID Sel) {
3085 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3086}
3087
3088}
3089
3090/// Check for invalid uses of an abstract type in a method declaration.
3091static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3092 CXXMethodDecl *MD) {
3093 // No need to do the check on definitions, which require that
3094 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003095 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003096 return;
3097
3098 // For safety's sake, just ignore it if we don't have type source
3099 // information. This should never happen for non-implicit methods,
3100 // but...
3101 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3102 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3103}
3104
3105/// Check for invalid uses of an abstract type within a class definition.
3106static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3107 CXXRecordDecl *RD) {
3108 for (CXXRecordDecl::decl_iterator
3109 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3110 Decl *D = *I;
3111 if (D->isImplicit()) continue;
3112
3113 // Methods and method templates.
3114 if (isa<CXXMethodDecl>(D)) {
3115 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3116 } else if (isa<FunctionTemplateDecl>(D)) {
3117 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3118 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3119
3120 // Fields and static variables.
3121 } else if (isa<FieldDecl>(D)) {
3122 FieldDecl *FD = cast<FieldDecl>(D);
3123 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3124 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3125 } else if (isa<VarDecl>(D)) {
3126 VarDecl *VD = cast<VarDecl>(D);
3127 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3128 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3129
3130 // Nested classes and class templates.
3131 } else if (isa<CXXRecordDecl>(D)) {
3132 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3133 } else if (isa<ClassTemplateDecl>(D)) {
3134 CheckAbstractClassUsage(Info,
3135 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3136 }
3137 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003138}
3139
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003140/// \brief Perform semantic checks on a class definition that has been
3141/// completing, introducing implicitly-declared members, checking for
3142/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003143void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003144 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003145 return;
3146
John McCall94c3b562010-08-18 09:41:07 +00003147 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3148 AbstractUsageInfo Info(*this, Record);
3149 CheckAbstractClassUsage(Info, Record);
3150 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003151
3152 // If this is not an aggregate type and has no user-declared constructor,
3153 // complain about any non-static data members of reference or const scalar
3154 // type, since they will never get initializers.
3155 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3156 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3157 bool Complained = false;
3158 for (RecordDecl::field_iterator F = Record->field_begin(),
3159 FEnd = Record->field_end();
3160 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003161 if (F->hasInClassInitializer())
3162 continue;
3163
Douglas Gregor325e5932010-04-15 00:00:53 +00003164 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003165 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003166 if (!Complained) {
3167 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3168 << Record->getTagKind() << Record;
3169 Complained = true;
3170 }
3171
3172 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3173 << F->getType()->isReferenceType()
3174 << F->getDeclName();
3175 }
3176 }
3177 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003178
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003179 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003180 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003181
3182 if (Record->getIdentifier()) {
3183 // C++ [class.mem]p13:
3184 // If T is the name of a class, then each of the following shall have a
3185 // name different from T:
3186 // - every member of every anonymous union that is a member of class T.
3187 //
3188 // C++ [class.mem]p14:
3189 // In addition, if class T has a user-declared constructor (12.1), every
3190 // non-static data member of class T shall have a name different from T.
3191 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003192 R.first != R.second; ++R.first) {
3193 NamedDecl *D = *R.first;
3194 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3195 isa<IndirectFieldDecl>(D)) {
3196 Diag(D->getLocation(), diag::err_member_name_of_class)
3197 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003198 break;
3199 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003200 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003201 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003202
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003203 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003204 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003205 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003206 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003207 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3208 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3209 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003210
3211 // See if a method overloads virtual methods in a base
3212 /// class without overriding any.
3213 if (!Record->isDependentType()) {
3214 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3215 MEnd = Record->method_end();
3216 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003217 if (!(*M)->isStatic())
3218 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003219 }
3220 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003221
3222 // Declare inherited constructors. We do this eagerly here because:
3223 // - The standard requires an eager diagnostic for conflicting inherited
3224 // constructors from different classes.
3225 // - The lazy declaration of the other implicit constructors is so as to not
3226 // waste space and performance on classes that are not meant to be
3227 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3228 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003229 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003230
Sean Hunteb88ae52011-05-23 21:07:59 +00003231 if (!Record->isDependentType())
3232 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003233}
3234
3235void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003236 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3237 ME = Record->method_end();
3238 MI != ME; ++MI) {
3239 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3240 switch (getSpecialMember(*MI)) {
3241 case CXXDefaultConstructor:
3242 CheckExplicitlyDefaultedDefaultConstructor(
3243 cast<CXXConstructorDecl>(*MI));
3244 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003245
Sean Huntcb45a0f2011-05-12 22:46:25 +00003246 case CXXDestructor:
3247 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3248 break;
3249
3250 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003251 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3252 break;
3253
Sean Huntcb45a0f2011-05-12 22:46:25 +00003254 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003255 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003256 break;
3257
Sean Hunt82713172011-05-25 23:16:36 +00003258 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003259 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003260 break;
3261
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003262 case CXXMoveAssignment:
3263 CheckExplicitlyDefaultedMoveAssignment(*MI);
3264 break;
3265
3266 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003267 llvm_unreachable("non-special member explicitly defaulted!");
3268 }
Sean Hunt001cad92011-05-10 00:49:42 +00003269 }
3270 }
3271
Sean Hunt001cad92011-05-10 00:49:42 +00003272}
3273
3274void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3275 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3276
3277 // Whether this was the first-declared instance of the constructor.
3278 // This affects whether we implicitly add an exception spec (and, eventually,
3279 // constexpr). It is also ill-formed to explicitly default a constructor such
3280 // that it would be deleted. (C++0x [decl.fct.def.default])
3281 bool First = CD == CD->getCanonicalDecl();
3282
Sean Hunt49634cf2011-05-13 06:10:58 +00003283 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003284 if (CD->getNumParams() != 0) {
3285 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3286 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003287 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003288 }
3289
3290 ImplicitExceptionSpecification Spec
3291 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3292 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003293 if (EPI.ExceptionSpecType == EST_Delayed) {
3294 // Exception specification depends on some deferred part of the class. We'll
3295 // try again when the class's definition has been fully processed.
3296 return;
3297 }
Sean Hunt001cad92011-05-10 00:49:42 +00003298 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3299 *ExceptionType = Context.getFunctionType(
3300 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3301
3302 if (CtorType->hasExceptionSpec()) {
3303 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003304 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003305 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003306 PDiag(),
3307 ExceptionType, SourceLocation(),
3308 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003309 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003310 }
3311 } else if (First) {
3312 // We set the declaration to have the computed exception spec here.
3313 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003314 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003315 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3316 }
Sean Huntca46d132011-05-12 03:51:48 +00003317
Sean Hunt49634cf2011-05-13 06:10:58 +00003318 if (HadError) {
3319 CD->setInvalidDecl();
3320 return;
3321 }
3322
Sean Huntca46d132011-05-12 03:51:48 +00003323 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003324 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003325 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003326 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003327 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003328 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003329 CD->setInvalidDecl();
3330 }
3331 }
3332}
3333
3334void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3335 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3336
3337 // Whether this was the first-declared instance of the constructor.
3338 bool First = CD == CD->getCanonicalDecl();
3339
3340 bool HadError = false;
3341 if (CD->getNumParams() != 1) {
3342 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3343 << CD->getSourceRange();
3344 HadError = true;
3345 }
3346
3347 ImplicitExceptionSpecification Spec(Context);
3348 bool Const;
3349 llvm::tie(Spec, Const) =
3350 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3351
3352 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3353 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3354 *ExceptionType = Context.getFunctionType(
3355 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3356
3357 // Check for parameter type matching.
3358 // This is a copy ctor so we know it's a cv-qualified reference to T.
3359 QualType ArgType = CtorType->getArgType(0);
3360 if (ArgType->getPointeeType().isVolatileQualified()) {
3361 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3362 HadError = true;
3363 }
3364 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3365 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3366 HadError = true;
3367 }
3368
3369 if (CtorType->hasExceptionSpec()) {
3370 if (CheckEquivalentExceptionSpec(
3371 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003372 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003373 PDiag(),
3374 ExceptionType, SourceLocation(),
3375 CtorType, CD->getLocation())) {
3376 HadError = true;
3377 }
3378 } else if (First) {
3379 // We set the declaration to have the computed exception spec here.
3380 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003381 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003382 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3383 }
3384
3385 if (HadError) {
3386 CD->setInvalidDecl();
3387 return;
3388 }
3389
3390 if (ShouldDeleteCopyConstructor(CD)) {
3391 if (First) {
3392 CD->setDeletedAsWritten();
3393 } else {
3394 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003395 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003396 CD->setInvalidDecl();
3397 }
Sean Huntca46d132011-05-12 03:51:48 +00003398 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003399}
Sean Hunt001cad92011-05-10 00:49:42 +00003400
Sean Hunt2b188082011-05-14 05:23:28 +00003401void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3402 assert(MD->isExplicitlyDefaulted());
3403
3404 // Whether this was the first-declared instance of the operator
3405 bool First = MD == MD->getCanonicalDecl();
3406
3407 bool HadError = false;
3408 if (MD->getNumParams() != 1) {
3409 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3410 << MD->getSourceRange();
3411 HadError = true;
3412 }
3413
3414 QualType ReturnType =
3415 MD->getType()->getAs<FunctionType>()->getResultType();
3416 if (!ReturnType->isLValueReferenceType() ||
3417 !Context.hasSameType(
3418 Context.getCanonicalType(ReturnType->getPointeeType()),
3419 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3420 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3421 HadError = true;
3422 }
3423
3424 ImplicitExceptionSpecification Spec(Context);
3425 bool Const;
3426 llvm::tie(Spec, Const) =
3427 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3428
3429 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3430 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3431 *ExceptionType = Context.getFunctionType(
3432 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3433
Sean Hunt2b188082011-05-14 05:23:28 +00003434 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003435 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003436 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003437 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003438 } else {
3439 if (ArgType->getPointeeType().isVolatileQualified()) {
3440 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3441 HadError = true;
3442 }
3443 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3444 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3445 HadError = true;
3446 }
Sean Hunt2b188082011-05-14 05:23:28 +00003447 }
Sean Huntbe631222011-05-17 20:44:43 +00003448
Sean Hunt2b188082011-05-14 05:23:28 +00003449 if (OperType->getTypeQuals()) {
3450 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3451 HadError = true;
3452 }
3453
3454 if (OperType->hasExceptionSpec()) {
3455 if (CheckEquivalentExceptionSpec(
3456 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003457 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003458 PDiag(),
3459 ExceptionType, SourceLocation(),
3460 OperType, MD->getLocation())) {
3461 HadError = true;
3462 }
3463 } else if (First) {
3464 // We set the declaration to have the computed exception spec here.
3465 // We duplicate the one parameter type.
3466 EPI.RefQualifier = OperType->getRefQualifier();
3467 EPI.ExtInfo = OperType->getExtInfo();
3468 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3469 }
3470
3471 if (HadError) {
3472 MD->setInvalidDecl();
3473 return;
3474 }
3475
3476 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3477 if (First) {
3478 MD->setDeletedAsWritten();
3479 } else {
3480 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003481 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003482 MD->setInvalidDecl();
3483 }
3484 }
3485}
3486
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003487void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3488 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3489
3490 // Whether this was the first-declared instance of the constructor.
3491 bool First = CD == CD->getCanonicalDecl();
3492
3493 bool HadError = false;
3494 if (CD->getNumParams() != 1) {
3495 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3496 << CD->getSourceRange();
3497 HadError = true;
3498 }
3499
3500 ImplicitExceptionSpecification Spec(
3501 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3502
3503 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3504 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3505 *ExceptionType = Context.getFunctionType(
3506 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3507
3508 // Check for parameter type matching.
3509 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3510 QualType ArgType = CtorType->getArgType(0);
3511 if (ArgType->getPointeeType().isVolatileQualified()) {
3512 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3513 HadError = true;
3514 }
3515 if (ArgType->getPointeeType().isConstQualified()) {
3516 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3517 HadError = true;
3518 }
3519
3520 if (CtorType->hasExceptionSpec()) {
3521 if (CheckEquivalentExceptionSpec(
3522 PDiag(diag::err_incorrect_defaulted_exception_spec)
3523 << CXXMoveConstructor,
3524 PDiag(),
3525 ExceptionType, SourceLocation(),
3526 CtorType, CD->getLocation())) {
3527 HadError = true;
3528 }
3529 } else if (First) {
3530 // We set the declaration to have the computed exception spec here.
3531 // We duplicate the one parameter type.
3532 EPI.ExtInfo = CtorType->getExtInfo();
3533 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3534 }
3535
3536 if (HadError) {
3537 CD->setInvalidDecl();
3538 return;
3539 }
3540
3541 if (ShouldDeleteMoveConstructor(CD)) {
3542 if (First) {
3543 CD->setDeletedAsWritten();
3544 } else {
3545 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3546 << CXXMoveConstructor;
3547 CD->setInvalidDecl();
3548 }
3549 }
3550}
3551
3552void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3553 assert(MD->isExplicitlyDefaulted());
3554
3555 // Whether this was the first-declared instance of the operator
3556 bool First = MD == MD->getCanonicalDecl();
3557
3558 bool HadError = false;
3559 if (MD->getNumParams() != 1) {
3560 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3561 << MD->getSourceRange();
3562 HadError = true;
3563 }
3564
3565 QualType ReturnType =
3566 MD->getType()->getAs<FunctionType>()->getResultType();
3567 if (!ReturnType->isLValueReferenceType() ||
3568 !Context.hasSameType(
3569 Context.getCanonicalType(ReturnType->getPointeeType()),
3570 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3571 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3572 HadError = true;
3573 }
3574
3575 ImplicitExceptionSpecification Spec(
3576 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3577
3578 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3579 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3580 *ExceptionType = Context.getFunctionType(
3581 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3582
3583 QualType ArgType = OperType->getArgType(0);
3584 if (!ArgType->isRValueReferenceType()) {
3585 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3586 HadError = true;
3587 } else {
3588 if (ArgType->getPointeeType().isVolatileQualified()) {
3589 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3590 HadError = true;
3591 }
3592 if (ArgType->getPointeeType().isConstQualified()) {
3593 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3594 HadError = true;
3595 }
3596 }
3597
3598 if (OperType->getTypeQuals()) {
3599 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3600 HadError = true;
3601 }
3602
3603 if (OperType->hasExceptionSpec()) {
3604 if (CheckEquivalentExceptionSpec(
3605 PDiag(diag::err_incorrect_defaulted_exception_spec)
3606 << CXXMoveAssignment,
3607 PDiag(),
3608 ExceptionType, SourceLocation(),
3609 OperType, MD->getLocation())) {
3610 HadError = true;
3611 }
3612 } else if (First) {
3613 // We set the declaration to have the computed exception spec here.
3614 // We duplicate the one parameter type.
3615 EPI.RefQualifier = OperType->getRefQualifier();
3616 EPI.ExtInfo = OperType->getExtInfo();
3617 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3618 }
3619
3620 if (HadError) {
3621 MD->setInvalidDecl();
3622 return;
3623 }
3624
3625 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3626 if (First) {
3627 MD->setDeletedAsWritten();
3628 } else {
3629 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3630 << CXXMoveAssignment;
3631 MD->setInvalidDecl();
3632 }
3633 }
3634}
3635
Sean Huntcb45a0f2011-05-12 22:46:25 +00003636void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3637 assert(DD->isExplicitlyDefaulted());
3638
3639 // Whether this was the first-declared instance of the destructor.
3640 bool First = DD == DD->getCanonicalDecl();
3641
3642 ImplicitExceptionSpecification Spec
3643 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3644 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3645 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3646 *ExceptionType = Context.getFunctionType(
3647 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3648
3649 if (DtorType->hasExceptionSpec()) {
3650 if (CheckEquivalentExceptionSpec(
3651 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003652 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003653 PDiag(),
3654 ExceptionType, SourceLocation(),
3655 DtorType, DD->getLocation())) {
3656 DD->setInvalidDecl();
3657 return;
3658 }
3659 } else if (First) {
3660 // We set the declaration to have the computed exception spec here.
3661 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003662 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003663 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3664 }
3665
3666 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003667 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003668 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003669 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003670 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003671 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003672 DD->setInvalidDecl();
3673 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003674 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003675}
3676
Sean Huntcdee3fe2011-05-11 22:34:38 +00003677bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3678 CXXRecordDecl *RD = CD->getParent();
3679 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003680 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003681 return false;
3682
Sean Hunt71a682f2011-05-18 03:41:58 +00003683 SourceLocation Loc = CD->getLocation();
3684
Sean Huntcdee3fe2011-05-11 22:34:38 +00003685 // Do access control from the constructor
3686 ContextRAII CtorContext(*this, CD);
3687
3688 bool Union = RD->isUnion();
3689 bool AllConst = true;
3690
Sean Huntcdee3fe2011-05-11 22:34:38 +00003691 // We do this because we should never actually use an anonymous
3692 // union's constructor.
3693 if (Union && RD->isAnonymousStructOrUnion())
3694 return false;
3695
3696 // FIXME: We should put some diagnostic logic right into this function.
3697
3698 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003699 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003700
3701 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3702 BE = RD->bases_end();
3703 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003704 // We'll handle this one later
3705 if (BI->isVirtual())
3706 continue;
3707
Sean Huntcdee3fe2011-05-11 22:34:38 +00003708 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3709 assert(BaseDecl && "base isn't a CXXRecordDecl");
3710
3711 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003712 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003713 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3714 if (BaseDtor->isDeleted())
3715 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003716 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003717 AR_accessible)
3718 return true;
3719
Sean Huntcdee3fe2011-05-11 22:34:38 +00003720 // -- any [direct base class either] has no default constructor or
3721 // overload resolution as applied to [its] default constructor
3722 // results in an ambiguity or in a function that is deleted or
3723 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003724 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3725 if (!BaseDefault || BaseDefault->isDeleted())
3726 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003727
Sean Huntb320e0c2011-06-10 03:50:41 +00003728 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3729 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003730 return true;
3731 }
3732
3733 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3734 BE = RD->vbases_end();
3735 BI != BE; ++BI) {
3736 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3737 assert(BaseDecl && "base isn't a CXXRecordDecl");
3738
3739 // -- any [virtual base class] has a type with a destructor that is
3740 // delete or inaccessible from the defaulted default constructor
3741 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3742 if (BaseDtor->isDeleted())
3743 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003744 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003745 AR_accessible)
3746 return true;
3747
3748 // -- any [virtual base class either] has no default constructor or
3749 // overload resolution as applied to [its] default constructor
3750 // results in an ambiguity or in a function that is deleted or
3751 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003752 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3753 if (!BaseDefault || BaseDefault->isDeleted())
3754 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003755
Sean Huntb320e0c2011-06-10 03:50:41 +00003756 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3757 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003758 return true;
3759 }
3760
3761 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3762 FE = RD->field_end();
3763 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003764 if (FI->isInvalidDecl())
3765 continue;
3766
Sean Huntcdee3fe2011-05-11 22:34:38 +00003767 QualType FieldType = Context.getBaseElementType(FI->getType());
3768 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003769
Sean Huntcdee3fe2011-05-11 22:34:38 +00003770 // -- any non-static data member with no brace-or-equal-initializer is of
3771 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003772 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003773 return true;
3774
3775 // -- X is a union and all its variant members are of const-qualified type
3776 // (or array thereof)
3777 if (Union && !FieldType.isConstQualified())
3778 AllConst = false;
3779
3780 if (FieldRecord) {
3781 // -- X is a union-like class that has a variant member with a non-trivial
3782 // default constructor
3783 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3784 return true;
3785
3786 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3787 if (FieldDtor->isDeleted())
3788 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003789 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003790 AR_accessible)
3791 return true;
3792
3793 // -- any non-variant non-static data member of const-qualified type (or
3794 // array thereof) with no brace-or-equal-initializer does not have a
3795 // user-provided default constructor
3796 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003797 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003798 !FieldRecord->hasUserProvidedDefaultConstructor())
3799 return true;
3800
3801 if (!Union && FieldRecord->isUnion() &&
3802 FieldRecord->isAnonymousStructOrUnion()) {
3803 // We're okay to reuse AllConst here since we only care about the
3804 // value otherwise if we're in a union.
3805 AllConst = true;
3806
3807 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3808 UE = FieldRecord->field_end();
3809 UI != UE; ++UI) {
3810 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3811 CXXRecordDecl *UnionFieldRecord =
3812 UnionFieldType->getAsCXXRecordDecl();
3813
3814 if (!UnionFieldType.isConstQualified())
3815 AllConst = false;
3816
3817 if (UnionFieldRecord &&
3818 !UnionFieldRecord->hasTrivialDefaultConstructor())
3819 return true;
3820 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003821
Sean Huntcdee3fe2011-05-11 22:34:38 +00003822 if (AllConst)
3823 return true;
3824
3825 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003826 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003827 continue;
3828 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003829
Richard Smith7a614d82011-06-11 17:19:42 +00003830 // -- any non-static data member with no brace-or-equal-initializer has
3831 // class type M (or array thereof) and either M has no default
3832 // constructor or overload resolution as applied to M's default
3833 // constructor results in an ambiguity or in a function that is deleted
3834 // or inaccessible from the defaulted default constructor.
3835 if (!FI->hasInClassInitializer()) {
3836 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3837 if (!FieldDefault || FieldDefault->isDeleted())
3838 return true;
3839 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3840 PDiag()) != AR_accessible)
3841 return true;
3842 }
3843 } else if (!Union && FieldType.isConstQualified() &&
3844 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003845 // -- any non-variant non-static data member of const-qualified type (or
3846 // array thereof) with no brace-or-equal-initializer does not have a
3847 // user-provided default constructor
3848 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003849 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003850 }
3851
3852 if (Union && AllConst)
3853 return true;
3854
3855 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003856}
3857
Sean Hunt49634cf2011-05-13 06:10:58 +00003858bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003859 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003860 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003861 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003862 return false;
3863
Sean Hunt71a682f2011-05-18 03:41:58 +00003864 SourceLocation Loc = CD->getLocation();
3865
Sean Hunt49634cf2011-05-13 06:10:58 +00003866 // Do access control from the constructor
3867 ContextRAII CtorContext(*this, CD);
3868
Sean Huntc530d172011-06-10 04:44:37 +00003869 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003870
Sean Hunt2b188082011-05-14 05:23:28 +00003871 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3872 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003873 unsigned ArgQuals =
3874 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3875 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003876
3877 // We do this because we should never actually use an anonymous
3878 // union's constructor.
3879 if (Union && RD->isAnonymousStructOrUnion())
3880 return false;
3881
3882 // FIXME: We should put some diagnostic logic right into this function.
3883
3884 // C++0x [class.copy]/11
3885 // A defaulted [copy] constructor for class X is defined as delete if X has:
3886
3887 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3888 BE = RD->bases_end();
3889 BI != BE; ++BI) {
3890 // We'll handle this one later
3891 if (BI->isVirtual())
3892 continue;
3893
3894 QualType BaseType = BI->getType();
3895 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3896 assert(BaseDecl && "base isn't a CXXRecordDecl");
3897
3898 // -- any [direct base class] of a type with a destructor that is deleted or
3899 // inaccessible from the defaulted constructor
3900 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3901 if (BaseDtor->isDeleted())
3902 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003903 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003904 AR_accessible)
3905 return true;
3906
3907 // -- a [direct base class] B that cannot be [copied] because overload
3908 // resolution, as applied to B's [copy] constructor, results in an
3909 // ambiguity or a function that is deleted or inaccessible from the
3910 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003911 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003912 if (!BaseCtor || BaseCtor->isDeleted())
3913 return true;
3914 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3915 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003916 return true;
3917 }
3918
3919 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3920 BE = RD->vbases_end();
3921 BI != BE; ++BI) {
3922 QualType BaseType = BI->getType();
3923 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3924 assert(BaseDecl && "base isn't a CXXRecordDecl");
3925
Sean Huntb320e0c2011-06-10 03:50:41 +00003926 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003927 // inaccessible from the defaulted constructor
3928 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3929 if (BaseDtor->isDeleted())
3930 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003931 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003932 AR_accessible)
3933 return true;
3934
3935 // -- a [virtual base class] B that cannot be [copied] because overload
3936 // resolution, as applied to B's [copy] constructor, results in an
3937 // ambiguity or a function that is deleted or inaccessible from the
3938 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003939 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003940 if (!BaseCtor || BaseCtor->isDeleted())
3941 return true;
3942 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3943 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003944 return true;
3945 }
3946
3947 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3948 FE = RD->field_end();
3949 FI != FE; ++FI) {
3950 QualType FieldType = Context.getBaseElementType(FI->getType());
3951
3952 // -- for a copy constructor, a non-static data member of rvalue reference
3953 // type
3954 if (FieldType->isRValueReferenceType())
3955 return true;
3956
3957 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3958
3959 if (FieldRecord) {
3960 // This is an anonymous union
3961 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3962 // Anonymous unions inside unions do not variant members create
3963 if (!Union) {
3964 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3965 UE = FieldRecord->field_end();
3966 UI != UE; ++UI) {
3967 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3968 CXXRecordDecl *UnionFieldRecord =
3969 UnionFieldType->getAsCXXRecordDecl();
3970
3971 // -- a variant member with a non-trivial [copy] constructor and X
3972 // is a union-like class
3973 if (UnionFieldRecord &&
3974 !UnionFieldRecord->hasTrivialCopyConstructor())
3975 return true;
3976 }
3977 }
3978
3979 // Don't try to initalize an anonymous union
3980 continue;
3981 } else {
3982 // -- a variant member with a non-trivial [copy] constructor and X is a
3983 // union-like class
3984 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3985 return true;
3986
3987 // -- any [non-static data member] of a type with a destructor that is
3988 // deleted or inaccessible from the defaulted constructor
3989 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3990 if (FieldDtor->isDeleted())
3991 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003992 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003993 AR_accessible)
3994 return true;
3995 }
Sean Huntc530d172011-06-10 04:44:37 +00003996
3997 // -- a [non-static data member of class type (or array thereof)] B that
3998 // cannot be [copied] because overload resolution, as applied to B's
3999 // [copy] constructor, results in an ambiguity or a function that is
4000 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00004001 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4002 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00004003 if (!FieldCtor || FieldCtor->isDeleted())
4004 return true;
4005 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4006 PDiag()) != AR_accessible)
4007 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00004008 }
Sean Hunt49634cf2011-05-13 06:10:58 +00004009 }
4010
4011 return false;
4012}
4013
Sean Hunt7f410192011-05-14 05:23:24 +00004014bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4015 CXXRecordDecl *RD = MD->getParent();
4016 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004017 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004018 return false;
4019
Sean Hunt71a682f2011-05-18 03:41:58 +00004020 SourceLocation Loc = MD->getLocation();
4021
Sean Hunt7f410192011-05-14 05:23:24 +00004022 // Do access control from the constructor
4023 ContextRAII MethodContext(*this, MD);
4024
4025 bool Union = RD->isUnion();
4026
Sean Hunt661c67a2011-06-21 23:42:56 +00004027 unsigned ArgQuals =
4028 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4029 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004030
4031 // We do this because we should never actually use an anonymous
4032 // union's constructor.
4033 if (Union && RD->isAnonymousStructOrUnion())
4034 return false;
4035
Sean Hunt7f410192011-05-14 05:23:24 +00004036 // FIXME: We should put some diagnostic logic right into this function.
4037
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004038 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004039 // A defaulted [copy] assignment operator for class X is defined as deleted
4040 // if X has:
4041
4042 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4043 BE = RD->bases_end();
4044 BI != BE; ++BI) {
4045 // We'll handle this one later
4046 if (BI->isVirtual())
4047 continue;
4048
4049 QualType BaseType = BI->getType();
4050 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4051 assert(BaseDecl && "base isn't a CXXRecordDecl");
4052
4053 // -- a [direct base class] B that cannot be [copied] because overload
4054 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004055 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004056 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004057 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4058 0);
4059 if (!CopyOper || CopyOper->isDeleted())
4060 return true;
4061 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004062 return true;
4063 }
4064
4065 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4066 BE = RD->vbases_end();
4067 BI != BE; ++BI) {
4068 QualType BaseType = BI->getType();
4069 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4070 assert(BaseDecl && "base isn't a CXXRecordDecl");
4071
Sean Hunt7f410192011-05-14 05:23:24 +00004072 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004073 // resolution, as applied to B's [copy] assignment operator, results in
4074 // an ambiguity or a function that is deleted or inaccessible from the
4075 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004076 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4077 0);
4078 if (!CopyOper || CopyOper->isDeleted())
4079 return true;
4080 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004081 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004082 }
4083
4084 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4085 FE = RD->field_end();
4086 FI != FE; ++FI) {
4087 QualType FieldType = Context.getBaseElementType(FI->getType());
4088
4089 // -- a non-static data member of reference type
4090 if (FieldType->isReferenceType())
4091 return true;
4092
4093 // -- a non-static data member of const non-class type (or array thereof)
4094 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4095 return true;
4096
4097 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4098
4099 if (FieldRecord) {
4100 // This is an anonymous union
4101 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4102 // Anonymous unions inside unions do not variant members create
4103 if (!Union) {
4104 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4105 UE = FieldRecord->field_end();
4106 UI != UE; ++UI) {
4107 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4108 CXXRecordDecl *UnionFieldRecord =
4109 UnionFieldType->getAsCXXRecordDecl();
4110
4111 // -- a variant member with a non-trivial [copy] assignment operator
4112 // and X is a union-like class
4113 if (UnionFieldRecord &&
4114 !UnionFieldRecord->hasTrivialCopyAssignment())
4115 return true;
4116 }
4117 }
4118
4119 // Don't try to initalize an anonymous union
4120 continue;
4121 // -- a variant member with a non-trivial [copy] assignment operator
4122 // and X is a union-like class
4123 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4124 return true;
4125 }
Sean Hunt7f410192011-05-14 05:23:24 +00004126
Sean Hunt661c67a2011-06-21 23:42:56 +00004127 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4128 false, 0);
4129 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004130 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004131 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004132 return true;
4133 }
4134 }
4135
4136 return false;
4137}
4138
4139bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4140 CXXRecordDecl *RD = CD->getParent();
4141 assert(!RD->isDependentType() && "do deletion after instantiation");
4142 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4143 return false;
4144
4145 SourceLocation Loc = CD->getLocation();
4146
4147 // Do access control from the constructor
4148 ContextRAII CtorContext(*this, CD);
4149
4150 bool Union = RD->isUnion();
4151
4152 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4153 "copy assignment arg has no pointee type");
4154
4155 // We do this because we should never actually use an anonymous
4156 // union's constructor.
4157 if (Union && RD->isAnonymousStructOrUnion())
4158 return false;
4159
4160 // C++0x [class.copy]/11
4161 // A defaulted [move] constructor for class X is defined as deleted
4162 // if X has:
4163
4164 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4165 BE = RD->bases_end();
4166 BI != BE; ++BI) {
4167 // We'll handle this one later
4168 if (BI->isVirtual())
4169 continue;
4170
4171 QualType BaseType = BI->getType();
4172 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4173 assert(BaseDecl && "base isn't a CXXRecordDecl");
4174
4175 // -- any [direct base class] of a type with a destructor that is deleted or
4176 // inaccessible from the defaulted constructor
4177 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4178 if (BaseDtor->isDeleted())
4179 return true;
4180 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4181 AR_accessible)
4182 return true;
4183
4184 // -- a [direct base class] B that cannot be [moved] because overload
4185 // resolution, as applied to B's [move] constructor, results in an
4186 // ambiguity or a function that is deleted or inaccessible from the
4187 // defaulted constructor
4188 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4189 if (!BaseCtor || BaseCtor->isDeleted())
4190 return true;
4191 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4192 AR_accessible)
4193 return true;
4194
4195 // -- for a move constructor, a [direct base class] with a type that
4196 // does not have a move constructor and is not trivially copyable.
4197 // If the field isn't a record, it's always trivially copyable.
4198 // A moving constructor could be a copy constructor instead.
4199 if (!BaseCtor->isMoveConstructor() &&
4200 !BaseDecl->isTriviallyCopyable())
4201 return true;
4202 }
4203
4204 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4205 BE = RD->vbases_end();
4206 BI != BE; ++BI) {
4207 QualType BaseType = BI->getType();
4208 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4209 assert(BaseDecl && "base isn't a CXXRecordDecl");
4210
4211 // -- any [virtual base class] of a type with a destructor that is deleted
4212 // or inaccessible from the defaulted constructor
4213 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4214 if (BaseDtor->isDeleted())
4215 return true;
4216 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4217 AR_accessible)
4218 return true;
4219
4220 // -- a [virtual base class] B that cannot be [moved] because overload
4221 // resolution, as applied to B's [move] constructor, results in an
4222 // ambiguity or a function that is deleted or inaccessible from the
4223 // defaulted constructor
4224 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4225 if (!BaseCtor || BaseCtor->isDeleted())
4226 return true;
4227 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4228 AR_accessible)
4229 return true;
4230
4231 // -- for a move constructor, a [virtual base class] with a type that
4232 // does not have a move constructor and is not trivially copyable.
4233 // If the field isn't a record, it's always trivially copyable.
4234 // A moving constructor could be a copy constructor instead.
4235 if (!BaseCtor->isMoveConstructor() &&
4236 !BaseDecl->isTriviallyCopyable())
4237 return true;
4238 }
4239
4240 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4241 FE = RD->field_end();
4242 FI != FE; ++FI) {
4243 QualType FieldType = Context.getBaseElementType(FI->getType());
4244
4245 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4246 // This is an anonymous union
4247 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4248 // Anonymous unions inside unions do not variant members create
4249 if (!Union) {
4250 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4251 UE = FieldRecord->field_end();
4252 UI != UE; ++UI) {
4253 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4254 CXXRecordDecl *UnionFieldRecord =
4255 UnionFieldType->getAsCXXRecordDecl();
4256
4257 // -- a variant member with a non-trivial [move] constructor and X
4258 // is a union-like class
4259 if (UnionFieldRecord &&
4260 !UnionFieldRecord->hasTrivialMoveConstructor())
4261 return true;
4262 }
4263 }
4264
4265 // Don't try to initalize an anonymous union
4266 continue;
4267 } else {
4268 // -- a variant member with a non-trivial [move] constructor and X is a
4269 // union-like class
4270 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4271 return true;
4272
4273 // -- any [non-static data member] of a type with a destructor that is
4274 // deleted or inaccessible from the defaulted constructor
4275 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4276 if (FieldDtor->isDeleted())
4277 return true;
4278 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4279 AR_accessible)
4280 return true;
4281 }
4282
4283 // -- a [non-static data member of class type (or array thereof)] B that
4284 // cannot be [moved] because overload resolution, as applied to B's
4285 // [move] constructor, results in an ambiguity or a function that is
4286 // deleted or inaccessible from the defaulted constructor
4287 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4288 if (!FieldCtor || FieldCtor->isDeleted())
4289 return true;
4290 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4291 PDiag()) != AR_accessible)
4292 return true;
4293
4294 // -- for a move constructor, a [non-static data member] with a type that
4295 // does not have a move constructor and is not trivially copyable.
4296 // If the field isn't a record, it's always trivially copyable.
4297 // A moving constructor could be a copy constructor instead.
4298 if (!FieldCtor->isMoveConstructor() &&
4299 !FieldRecord->isTriviallyCopyable())
4300 return true;
4301 }
4302 }
4303
4304 return false;
4305}
4306
4307bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4308 CXXRecordDecl *RD = MD->getParent();
4309 assert(!RD->isDependentType() && "do deletion after instantiation");
4310 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4311 return false;
4312
4313 SourceLocation Loc = MD->getLocation();
4314
4315 // Do access control from the constructor
4316 ContextRAII MethodContext(*this, MD);
4317
4318 bool Union = RD->isUnion();
4319
4320 // We do this because we should never actually use an anonymous
4321 // union's constructor.
4322 if (Union && RD->isAnonymousStructOrUnion())
4323 return false;
4324
4325 // C++0x [class.copy]/20
4326 // A defaulted [move] assignment operator for class X is defined as deleted
4327 // if X has:
4328
4329 // -- for the move constructor, [...] any direct or indirect virtual base
4330 // class.
4331 if (RD->getNumVBases() != 0)
4332 return true;
4333
4334 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4335 BE = RD->bases_end();
4336 BI != BE; ++BI) {
4337
4338 QualType BaseType = BI->getType();
4339 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4340 assert(BaseDecl && "base isn't a CXXRecordDecl");
4341
4342 // -- a [direct base class] B that cannot be [moved] because overload
4343 // resolution, as applied to B's [move] assignment operator, results in
4344 // an ambiguity or a function that is deleted or inaccessible from the
4345 // assignment operator
4346 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4347 if (!MoveOper || MoveOper->isDeleted())
4348 return true;
4349 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4350 return true;
4351
4352 // -- for the move assignment operator, a [direct base class] with a type
4353 // that does not have a move assignment operator and is not trivially
4354 // copyable.
4355 if (!MoveOper->isMoveAssignmentOperator() &&
4356 !BaseDecl->isTriviallyCopyable())
4357 return true;
4358 }
4359
4360 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4361 FE = RD->field_end();
4362 FI != FE; ++FI) {
4363 QualType FieldType = Context.getBaseElementType(FI->getType());
4364
4365 // -- a non-static data member of reference type
4366 if (FieldType->isReferenceType())
4367 return true;
4368
4369 // -- a non-static data member of const non-class type (or array thereof)
4370 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4371 return true;
4372
4373 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4374
4375 if (FieldRecord) {
4376 // This is an anonymous union
4377 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4378 // Anonymous unions inside unions do not variant members create
4379 if (!Union) {
4380 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4381 UE = FieldRecord->field_end();
4382 UI != UE; ++UI) {
4383 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4384 CXXRecordDecl *UnionFieldRecord =
4385 UnionFieldType->getAsCXXRecordDecl();
4386
4387 // -- a variant member with a non-trivial [move] assignment operator
4388 // and X is a union-like class
4389 if (UnionFieldRecord &&
4390 !UnionFieldRecord->hasTrivialMoveAssignment())
4391 return true;
4392 }
4393 }
4394
4395 // Don't try to initalize an anonymous union
4396 continue;
4397 // -- a variant member with a non-trivial [move] assignment operator
4398 // and X is a union-like class
4399 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4400 return true;
4401 }
4402
4403 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4404 if (!MoveOper || MoveOper->isDeleted())
4405 return true;
4406 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4407 return true;
4408
4409 // -- for the move assignment operator, a [non-static data member] with a
4410 // type that does not have a move assignment operator and is not
4411 // trivially copyable.
4412 if (!MoveOper->isMoveAssignmentOperator() &&
4413 !FieldRecord->isTriviallyCopyable())
4414 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004415 }
Sean Hunt7f410192011-05-14 05:23:24 +00004416 }
4417
4418 return false;
4419}
4420
Sean Huntcb45a0f2011-05-12 22:46:25 +00004421bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4422 CXXRecordDecl *RD = DD->getParent();
4423 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004424 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004425 return false;
4426
Sean Hunt71a682f2011-05-18 03:41:58 +00004427 SourceLocation Loc = DD->getLocation();
4428
Sean Huntcb45a0f2011-05-12 22:46:25 +00004429 // Do access control from the destructor
4430 ContextRAII CtorContext(*this, DD);
4431
4432 bool Union = RD->isUnion();
4433
Sean Hunt49634cf2011-05-13 06:10:58 +00004434 // We do this because we should never actually use an anonymous
4435 // union's destructor.
4436 if (Union && RD->isAnonymousStructOrUnion())
4437 return false;
4438
Sean Huntcb45a0f2011-05-12 22:46:25 +00004439 // C++0x [class.dtor]p5
4440 // A defaulted destructor for a class X is defined as deleted if:
4441 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4442 BE = RD->bases_end();
4443 BI != BE; ++BI) {
4444 // We'll handle this one later
4445 if (BI->isVirtual())
4446 continue;
4447
4448 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4449 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4450 assert(BaseDtor && "base has no destructor");
4451
4452 // -- any direct or virtual base class has a deleted destructor or
4453 // a destructor that is inaccessible from the defaulted destructor
4454 if (BaseDtor->isDeleted())
4455 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004456 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004457 AR_accessible)
4458 return true;
4459 }
4460
4461 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4462 BE = RD->vbases_end();
4463 BI != BE; ++BI) {
4464 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4465 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4466 assert(BaseDtor && "base has no destructor");
4467
4468 // -- any direct or virtual base class has a deleted destructor or
4469 // a destructor that is inaccessible from the defaulted destructor
4470 if (BaseDtor->isDeleted())
4471 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004472 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004473 AR_accessible)
4474 return true;
4475 }
4476
4477 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4478 FE = RD->field_end();
4479 FI != FE; ++FI) {
4480 QualType FieldType = Context.getBaseElementType(FI->getType());
4481 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4482 if (FieldRecord) {
4483 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4484 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4485 UE = FieldRecord->field_end();
4486 UI != UE; ++UI) {
4487 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4488 CXXRecordDecl *UnionFieldRecord =
4489 UnionFieldType->getAsCXXRecordDecl();
4490
4491 // -- X is a union-like class that has a variant member with a non-
4492 // trivial destructor.
4493 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4494 return true;
4495 }
4496 // Technically we are supposed to do this next check unconditionally.
4497 // But that makes absolutely no sense.
4498 } else {
4499 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4500
4501 // -- any of the non-static data members has class type M (or array
4502 // thereof) and M has a deleted destructor or a destructor that is
4503 // inaccessible from the defaulted destructor
4504 if (FieldDtor->isDeleted())
4505 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004506 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004507 AR_accessible)
4508 return true;
4509
4510 // -- X is a union-like class that has a variant member with a non-
4511 // trivial destructor.
4512 if (Union && !FieldDtor->isTrivial())
4513 return true;
4514 }
4515 }
4516 }
4517
4518 if (DD->isVirtual()) {
4519 FunctionDecl *OperatorDelete = 0;
4520 DeclarationName Name =
4521 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004522 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004523 false))
4524 return true;
4525 }
4526
4527
4528 return false;
4529}
4530
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004531/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004532namespace {
4533 struct FindHiddenVirtualMethodData {
4534 Sema *S;
4535 CXXMethodDecl *Method;
4536 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004537 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004538 };
4539}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004540
4541/// \brief Member lookup function that determines whether a given C++
4542/// method overloads virtual methods in a base class without overriding any,
4543/// to be used with CXXRecordDecl::lookupInBases().
4544static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4545 CXXBasePath &Path,
4546 void *UserData) {
4547 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4548
4549 FindHiddenVirtualMethodData &Data
4550 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4551
4552 DeclarationName Name = Data.Method->getDeclName();
4553 assert(Name.getNameKind() == DeclarationName::Identifier);
4554
4555 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004556 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004557 for (Path.Decls = BaseRecord->lookup(Name);
4558 Path.Decls.first != Path.Decls.second;
4559 ++Path.Decls.first) {
4560 NamedDecl *D = *Path.Decls.first;
4561 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004562 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004563 foundSameNameMethod = true;
4564 // Interested only in hidden virtual methods.
4565 if (!MD->isVirtual())
4566 continue;
4567 // If the method we are checking overrides a method from its base
4568 // don't warn about the other overloaded methods.
4569 if (!Data.S->IsOverload(Data.Method, MD, false))
4570 return true;
4571 // Collect the overload only if its hidden.
4572 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4573 overloadedMethods.push_back(MD);
4574 }
4575 }
4576
4577 if (foundSameNameMethod)
4578 Data.OverloadedMethods.append(overloadedMethods.begin(),
4579 overloadedMethods.end());
4580 return foundSameNameMethod;
4581}
4582
4583/// \brief See if a method overloads virtual methods in a base class without
4584/// overriding any.
4585void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4586 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4587 MD->getLocation()) == Diagnostic::Ignored)
4588 return;
4589 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4590 return;
4591
4592 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4593 /*bool RecordPaths=*/false,
4594 /*bool DetectVirtual=*/false);
4595 FindHiddenVirtualMethodData Data;
4596 Data.Method = MD;
4597 Data.S = this;
4598
4599 // Keep the base methods that were overriden or introduced in the subclass
4600 // by 'using' in a set. A base method not in this set is hidden.
4601 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4602 res.first != res.second; ++res.first) {
4603 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4604 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4605 E = MD->end_overridden_methods();
4606 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004607 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004608 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4609 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004610 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004611 }
4612
4613 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4614 !Data.OverloadedMethods.empty()) {
4615 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4616 << MD << (Data.OverloadedMethods.size() > 1);
4617
4618 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4619 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4620 Diag(overloadedMD->getLocation(),
4621 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4622 }
4623 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004624}
4625
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004626void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004627 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004628 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004629 SourceLocation RBrac,
4630 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004631 if (!TagDecl)
4632 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004633
Douglas Gregor42af25f2009-05-11 19:58:34 +00004634 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004635
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004636 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004637 // strict aliasing violation!
4638 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004639 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004640
Douglas Gregor23c94db2010-07-02 17:43:08 +00004641 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004642 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004643}
4644
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004645/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4646/// special functions, such as the default constructor, copy
4647/// constructor, or destructor, to the given C++ class (C++
4648/// [special]p1). This routine can only be executed just before the
4649/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004650void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004651 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004652 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004653
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004654 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004655 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004656
Douglas Gregora376d102010-07-02 21:50:04 +00004657 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4658 ++ASTContext::NumImplicitCopyAssignmentOperators;
4659
4660 // If we have a dynamic class, then the copy assignment operator may be
4661 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4662 // it shows up in the right place in the vtable and that we diagnose
4663 // problems with the implicit exception specification.
4664 if (ClassDecl->isDynamicClass())
4665 DeclareImplicitCopyAssignment(ClassDecl);
4666 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004667
Douglas Gregor4923aa22010-07-02 20:37:36 +00004668 if (!ClassDecl->hasUserDeclaredDestructor()) {
4669 ++ASTContext::NumImplicitDestructors;
4670
4671 // If we have a dynamic class, then the destructor may be virtual, so we
4672 // have to declare the destructor immediately. This ensures that, e.g., it
4673 // shows up in the right place in the vtable and that we diagnose problems
4674 // with the implicit exception specification.
4675 if (ClassDecl->isDynamicClass())
4676 DeclareImplicitDestructor(ClassDecl);
4677 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004678}
4679
Francois Pichet8387e2a2011-04-22 22:18:13 +00004680void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4681 if (!D)
4682 return;
4683
4684 int NumParamList = D->getNumTemplateParameterLists();
4685 for (int i = 0; i < NumParamList; i++) {
4686 TemplateParameterList* Params = D->getTemplateParameterList(i);
4687 for (TemplateParameterList::iterator Param = Params->begin(),
4688 ParamEnd = Params->end();
4689 Param != ParamEnd; ++Param) {
4690 NamedDecl *Named = cast<NamedDecl>(*Param);
4691 if (Named->getDeclName()) {
4692 S->AddDecl(Named);
4693 IdResolver.AddDecl(Named);
4694 }
4695 }
4696 }
4697}
4698
John McCalld226f652010-08-21 09:40:31 +00004699void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004700 if (!D)
4701 return;
4702
4703 TemplateParameterList *Params = 0;
4704 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4705 Params = Template->getTemplateParameters();
4706 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4707 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4708 Params = PartialSpec->getTemplateParameters();
4709 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004710 return;
4711
Douglas Gregor6569d682009-05-27 23:11:45 +00004712 for (TemplateParameterList::iterator Param = Params->begin(),
4713 ParamEnd = Params->end();
4714 Param != ParamEnd; ++Param) {
4715 NamedDecl *Named = cast<NamedDecl>(*Param);
4716 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004717 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004718 IdResolver.AddDecl(Named);
4719 }
4720 }
4721}
4722
John McCalld226f652010-08-21 09:40:31 +00004723void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004724 if (!RecordD) return;
4725 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004726 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004727 PushDeclContext(S, Record);
4728}
4729
John McCalld226f652010-08-21 09:40:31 +00004730void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004731 if (!RecordD) return;
4732 PopDeclContext();
4733}
4734
Douglas Gregor72b505b2008-12-16 21:30:33 +00004735/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4736/// parsing a top-level (non-nested) C++ class, and we are now
4737/// parsing those parts of the given Method declaration that could
4738/// not be parsed earlier (C++ [class.mem]p2), such as default
4739/// arguments. This action should enter the scope of the given
4740/// Method declaration as if we had just parsed the qualified method
4741/// name. However, it should not bring the parameters into scope;
4742/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004743void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004744}
4745
4746/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4747/// C++ method declaration. We're (re-)introducing the given
4748/// function parameter into scope for use in parsing later parts of
4749/// the method declaration. For example, we could see an
4750/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004751void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004752 if (!ParamD)
4753 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004754
John McCalld226f652010-08-21 09:40:31 +00004755 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004756
4757 // If this parameter has an unparsed default argument, clear it out
4758 // to make way for the parsed default argument.
4759 if (Param->hasUnparsedDefaultArg())
4760 Param->setDefaultArg(0);
4761
John McCalld226f652010-08-21 09:40:31 +00004762 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004763 if (Param->getDeclName())
4764 IdResolver.AddDecl(Param);
4765}
4766
4767/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4768/// processing the delayed method declaration for Method. The method
4769/// declaration is now considered finished. There may be a separate
4770/// ActOnStartOfFunctionDef action later (not necessarily
4771/// immediately!) for this method, if it was also defined inside the
4772/// class body.
John McCalld226f652010-08-21 09:40:31 +00004773void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004774 if (!MethodD)
4775 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004776
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004777 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004778
John McCalld226f652010-08-21 09:40:31 +00004779 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004780
4781 // Now that we have our default arguments, check the constructor
4782 // again. It could produce additional diagnostics or affect whether
4783 // the class has implicitly-declared destructors, among other
4784 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004785 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4786 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004787
4788 // Check the default arguments, which we may have added.
4789 if (!Method->isInvalidDecl())
4790 CheckCXXDefaultArguments(Method);
4791}
4792
Douglas Gregor42a552f2008-11-05 20:51:48 +00004793/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004794/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004795/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004796/// emit diagnostics and set the invalid bit to true. In any case, the type
4797/// will be updated to reflect a well-formed type for the constructor and
4798/// returned.
4799QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004800 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004801 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004802
4803 // C++ [class.ctor]p3:
4804 // A constructor shall not be virtual (10.3) or static (9.4). A
4805 // constructor can be invoked for a const, volatile or const
4806 // volatile object. A constructor shall not be declared const,
4807 // volatile, or const volatile (9.3.2).
4808 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004809 if (!D.isInvalidType())
4810 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4811 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4812 << SourceRange(D.getIdentifierLoc());
4813 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004814 }
John McCalld931b082010-08-26 03:08:43 +00004815 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004816 if (!D.isInvalidType())
4817 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4818 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4819 << SourceRange(D.getIdentifierLoc());
4820 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004821 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004822 }
Mike Stump1eb44332009-09-09 15:08:12 +00004823
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004824 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004825 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004826 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004827 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4828 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004829 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004830 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4831 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004832 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004833 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4834 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004835 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004836 }
Mike Stump1eb44332009-09-09 15:08:12 +00004837
Douglas Gregorc938c162011-01-26 05:01:58 +00004838 // C++0x [class.ctor]p4:
4839 // A constructor shall not be declared with a ref-qualifier.
4840 if (FTI.hasRefQualifier()) {
4841 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4842 << FTI.RefQualifierIsLValueRef
4843 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4844 D.setInvalidType();
4845 }
4846
Douglas Gregor42a552f2008-11-05 20:51:48 +00004847 // Rebuild the function type "R" without any type qualifiers (in
4848 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004849 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004850 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004851 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4852 return R;
4853
4854 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4855 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004856 EPI.RefQualifier = RQ_None;
4857
Chris Lattner65401802009-04-25 08:28:21 +00004858 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004859 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004860}
4861
Douglas Gregor72b505b2008-12-16 21:30:33 +00004862/// CheckConstructor - Checks a fully-formed constructor for
4863/// well-formedness, issuing any diagnostics required. Returns true if
4864/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004865void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004866 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004867 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4868 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004869 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004870
4871 // C++ [class.copy]p3:
4872 // A declaration of a constructor for a class X is ill-formed if
4873 // its first parameter is of type (optionally cv-qualified) X and
4874 // either there are no other parameters or else all other
4875 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004876 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004877 ((Constructor->getNumParams() == 1) ||
4878 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004879 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4880 Constructor->getTemplateSpecializationKind()
4881 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004882 QualType ParamType = Constructor->getParamDecl(0)->getType();
4883 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4884 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004885 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004886 const char *ConstRef
4887 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4888 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004889 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004890 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004891
4892 // FIXME: Rather that making the constructor invalid, we should endeavor
4893 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004894 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004895 }
4896 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004897}
4898
John McCall15442822010-08-04 01:04:25 +00004899/// CheckDestructor - Checks a fully-formed destructor definition for
4900/// well-formedness, issuing any diagnostics required. Returns true
4901/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004902bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004903 CXXRecordDecl *RD = Destructor->getParent();
4904
4905 if (Destructor->isVirtual()) {
4906 SourceLocation Loc;
4907
4908 if (!Destructor->isImplicit())
4909 Loc = Destructor->getLocation();
4910 else
4911 Loc = RD->getLocation();
4912
4913 // If we have a virtual destructor, look up the deallocation function
4914 FunctionDecl *OperatorDelete = 0;
4915 DeclarationName Name =
4916 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004917 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004918 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004919
4920 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004921
4922 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004923 }
Anders Carlsson37909802009-11-30 21:24:50 +00004924
4925 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004926}
4927
Mike Stump1eb44332009-09-09 15:08:12 +00004928static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004929FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4930 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4931 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004932 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004933}
4934
Douglas Gregor42a552f2008-11-05 20:51:48 +00004935/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4936/// the well-formednes of the destructor declarator @p D with type @p
4937/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004938/// emit diagnostics and set the declarator to invalid. Even if this happens,
4939/// will be updated to reflect a well-formed type for the destructor and
4940/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004941QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004942 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004943 // C++ [class.dtor]p1:
4944 // [...] A typedef-name that names a class is a class-name
4945 // (7.1.3); however, a typedef-name that names a class shall not
4946 // be used as the identifier in the declarator for a destructor
4947 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004948 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004949 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004950 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004951 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004952 else if (const TemplateSpecializationType *TST =
4953 DeclaratorType->getAs<TemplateSpecializationType>())
4954 if (TST->isTypeAlias())
4955 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4956 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004957
4958 // C++ [class.dtor]p2:
4959 // A destructor is used to destroy objects of its class type. A
4960 // destructor takes no parameters, and no return type can be
4961 // specified for it (not even void). The address of a destructor
4962 // shall not be taken. A destructor shall not be static. A
4963 // destructor can be invoked for a const, volatile or const
4964 // volatile object. A destructor shall not be declared const,
4965 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004966 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004967 if (!D.isInvalidType())
4968 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4969 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004970 << SourceRange(D.getIdentifierLoc())
4971 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4972
John McCalld931b082010-08-26 03:08:43 +00004973 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004974 }
Chris Lattner65401802009-04-25 08:28:21 +00004975 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004976 // Destructors don't have return types, but the parser will
4977 // happily parse something like:
4978 //
4979 // class X {
4980 // float ~X();
4981 // };
4982 //
4983 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004984 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4985 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4986 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004987 }
Mike Stump1eb44332009-09-09 15:08:12 +00004988
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004989 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004990 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004991 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4993 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004994 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004995 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4996 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004997 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004998 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4999 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005000 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005001 }
5002
Douglas Gregorc938c162011-01-26 05:01:58 +00005003 // C++0x [class.dtor]p2:
5004 // A destructor shall not be declared with a ref-qualifier.
5005 if (FTI.hasRefQualifier()) {
5006 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5007 << FTI.RefQualifierIsLValueRef
5008 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5009 D.setInvalidType();
5010 }
5011
Douglas Gregor42a552f2008-11-05 20:51:48 +00005012 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005013 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005014 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5015
5016 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005017 FTI.freeArgs();
5018 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005019 }
5020
Mike Stump1eb44332009-09-09 15:08:12 +00005021 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005022 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005023 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005024 D.setInvalidType();
5025 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005026
5027 // Rebuild the function type "R" without any type qualifiers or
5028 // parameters (in case any of the errors above fired) and with
5029 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005030 // types.
John McCalle23cf432010-12-14 08:05:40 +00005031 if (!D.isInvalidType())
5032 return R;
5033
Douglas Gregord92ec472010-07-01 05:10:53 +00005034 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005035 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5036 EPI.Variadic = false;
5037 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005038 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005039 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005040}
5041
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005042/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5043/// well-formednes of the conversion function declarator @p D with
5044/// type @p R. If there are any errors in the declarator, this routine
5045/// will emit diagnostics and return true. Otherwise, it will return
5046/// false. Either way, the type @p R will be updated to reflect a
5047/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005048void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005049 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005050 // C++ [class.conv.fct]p1:
5051 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005052 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005053 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005054 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005055 if (!D.isInvalidType())
5056 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5057 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5058 << SourceRange(D.getIdentifierLoc());
5059 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005060 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005061 }
John McCalla3f81372010-04-13 00:04:31 +00005062
5063 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5064
Chris Lattner6e475012009-04-25 08:35:12 +00005065 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005066 // Conversion functions don't have return types, but the parser will
5067 // happily parse something like:
5068 //
5069 // class X {
5070 // float operator bool();
5071 // };
5072 //
5073 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005074 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5075 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5076 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005077 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005078 }
5079
John McCalla3f81372010-04-13 00:04:31 +00005080 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5081
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005082 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005083 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005084 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5085
5086 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005087 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005088 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005089 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005090 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005091 D.setInvalidType();
5092 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005093
John McCalla3f81372010-04-13 00:04:31 +00005094 // Diagnose "&operator bool()" and other such nonsense. This
5095 // is actually a gcc extension which we don't support.
5096 if (Proto->getResultType() != ConvType) {
5097 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5098 << Proto->getResultType();
5099 D.setInvalidType();
5100 ConvType = Proto->getResultType();
5101 }
5102
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005103 // C++ [class.conv.fct]p4:
5104 // The conversion-type-id shall not represent a function type nor
5105 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005106 if (ConvType->isArrayType()) {
5107 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5108 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005109 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005110 } else if (ConvType->isFunctionType()) {
5111 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5112 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005113 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005114 }
5115
5116 // Rebuild the function type "R" without any parameters (in case any
5117 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005118 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005119 if (D.isInvalidType())
5120 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005121
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005122 // C++0x explicit conversion operators.
5123 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00005124 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005125 diag::warn_explicit_conversion_functions)
5126 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005127}
5128
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005129/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5130/// the declaration of the given C++ conversion function. This routine
5131/// is responsible for recording the conversion function in the C++
5132/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005133Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005134 assert(Conversion && "Expected to receive a conversion function declaration");
5135
Douglas Gregor9d350972008-12-12 08:25:50 +00005136 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005137
5138 // Make sure we aren't redeclaring the conversion function.
5139 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005140
5141 // C++ [class.conv.fct]p1:
5142 // [...] A conversion function is never used to convert a
5143 // (possibly cv-qualified) object to the (possibly cv-qualified)
5144 // same object type (or a reference to it), to a (possibly
5145 // cv-qualified) base class of that type (or a reference to it),
5146 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005147 // FIXME: Suppress this warning if the conversion function ends up being a
5148 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005149 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005150 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005151 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005152 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005153 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5154 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005155 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005156 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005157 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5158 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005159 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005160 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005161 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005162 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005163 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005164 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005165 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005166 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005167 }
5168
Douglas Gregore80622f2010-09-29 04:25:11 +00005169 if (FunctionTemplateDecl *ConversionTemplate
5170 = Conversion->getDescribedFunctionTemplate())
5171 return ConversionTemplate;
5172
John McCalld226f652010-08-21 09:40:31 +00005173 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005174}
5175
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005176//===----------------------------------------------------------------------===//
5177// Namespace Handling
5178//===----------------------------------------------------------------------===//
5179
John McCallea318642010-08-26 09:15:37 +00005180
5181
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005182/// ActOnStartNamespaceDef - This is called at the start of a namespace
5183/// definition.
John McCalld226f652010-08-21 09:40:31 +00005184Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005185 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005186 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005187 SourceLocation IdentLoc,
5188 IdentifierInfo *II,
5189 SourceLocation LBrace,
5190 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005191 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5192 // For anonymous namespace, take the location of the left brace.
5193 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00005194 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005195 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005196 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005197
5198 Scope *DeclRegionScope = NamespcScope->getParent();
5199
Anders Carlsson2a3503d2010-02-07 01:09:23 +00005200 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5201
John McCall90f14502010-12-10 02:59:44 +00005202 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5203 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005204
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005205 if (II) {
5206 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005207 // The identifier in an original-namespace-definition shall not
5208 // have been previously defined in the declarative region in
5209 // which the original-namespace-definition appears. The
5210 // identifier in an original-namespace-definition is the name of
5211 // the namespace. Subsequently in that declarative region, it is
5212 // treated as an original-namespace-name.
5213 //
5214 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005215 // look through using directives, just look for any ordinary names.
5216
5217 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5218 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5219 Decl::IDNS_Namespace;
5220 NamedDecl *PrevDecl = 0;
5221 for (DeclContext::lookup_result R
5222 = CurContext->getRedeclContext()->lookup(II);
5223 R.first != R.second; ++R.first) {
5224 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5225 PrevDecl = *R.first;
5226 break;
5227 }
5228 }
5229
Douglas Gregor44b43212008-12-11 16:49:14 +00005230 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5231 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005232 if (Namespc->isInline() != OrigNS->isInline()) {
5233 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005234 if (OrigNS->isInline()) {
5235 // The user probably just forgot the 'inline', so suggest that it
5236 // be added back.
5237 Diag(Namespc->getLocation(),
5238 diag::warn_inline_namespace_reopened_noninline)
5239 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5240 } else {
5241 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5242 << Namespc->isInline();
5243 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005244 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005245
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005246 // Recover by ignoring the new namespace's inline status.
5247 Namespc->setInline(OrigNS->isInline());
5248 }
5249
Douglas Gregor44b43212008-12-11 16:49:14 +00005250 // Attach this namespace decl to the chain of extended namespace
5251 // definitions.
5252 OrigNS->setNextNamespace(Namespc);
5253 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005254
Mike Stump1eb44332009-09-09 15:08:12 +00005255 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00005256 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00005257 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00005258 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005259 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005260 } else if (PrevDecl) {
5261 // This is an invalid name redefinition.
5262 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5263 << Namespc->getDeclName();
5264 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5265 Namespc->setInvalidDecl();
5266 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005267 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005268 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005269 // This is the first "real" definition of the namespace "std", so update
5270 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005271 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005272 // We had already defined a dummy namespace "std". Link this new
5273 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005274 StdNS->setNextNamespace(Namespc);
5275 StdNS->setLocation(IdentLoc);
5276 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005277 }
5278
5279 // Make our StdNamespace cache point at the first real definition of the
5280 // "std" namespace.
5281 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005282
5283 // Add this instance of "std" to the set of known namespaces
5284 KnownNamespaces[Namespc] = false;
5285 } else if (!Namespc->isInline()) {
5286 // Since this is an "original" namespace, add it to the known set of
5287 // namespaces if it is not an inline namespace.
5288 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005289 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005290
5291 PushOnScopeChains(Namespc, DeclRegionScope);
5292 } else {
John McCall9aeed322009-10-01 00:25:31 +00005293 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00005294 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00005295
5296 // Link the anonymous namespace into its parent.
5297 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005298 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005299 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5300 PrevDecl = TU->getAnonymousNamespace();
5301 TU->setAnonymousNamespace(Namespc);
5302 } else {
5303 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5304 PrevDecl = ND->getAnonymousNamespace();
5305 ND->setAnonymousNamespace(Namespc);
5306 }
5307
5308 // Link the anonymous namespace with its previous declaration.
5309 if (PrevDecl) {
5310 assert(PrevDecl->isAnonymousNamespace());
5311 assert(!PrevDecl->getNextNamespace());
5312 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5313 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005314
5315 if (Namespc->isInline() != PrevDecl->isInline()) {
5316 // inline-ness must match
5317 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5318 << Namespc->isInline();
5319 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5320 Namespc->setInvalidDecl();
5321 // Recover by ignoring the new namespace's inline status.
5322 Namespc->setInline(PrevDecl->isInline());
5323 }
John McCall5fdd7642009-12-16 02:06:49 +00005324 }
John McCall9aeed322009-10-01 00:25:31 +00005325
Douglas Gregora4181472010-03-24 00:46:35 +00005326 CurContext->addDecl(Namespc);
5327
John McCall9aeed322009-10-01 00:25:31 +00005328 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5329 // behaves as if it were replaced by
5330 // namespace unique { /* empty body */ }
5331 // using namespace unique;
5332 // namespace unique { namespace-body }
5333 // where all occurrences of 'unique' in a translation unit are
5334 // replaced by the same identifier and this identifier differs
5335 // from all other identifiers in the entire program.
5336
5337 // We just create the namespace with an empty name and then add an
5338 // implicit using declaration, just like the standard suggests.
5339 //
5340 // CodeGen enforces the "universally unique" aspect by giving all
5341 // declarations semantically contained within an anonymous
5342 // namespace internal linkage.
5343
John McCall5fdd7642009-12-16 02:06:49 +00005344 if (!PrevDecl) {
5345 UsingDirectiveDecl* UD
5346 = UsingDirectiveDecl::Create(Context, CurContext,
5347 /* 'using' */ LBrace,
5348 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005349 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005350 /* identifier */ SourceLocation(),
5351 Namespc,
5352 /* Ancestor */ CurContext);
5353 UD->setImplicit();
5354 CurContext->addDecl(UD);
5355 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005356 }
5357
5358 // Although we could have an invalid decl (i.e. the namespace name is a
5359 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005360 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5361 // for the namespace has the declarations that showed up in that particular
5362 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005363 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005364 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005365}
5366
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005367/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5368/// is a namespace alias, returns the namespace it points to.
5369static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5370 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5371 return AD->getNamespace();
5372 return dyn_cast_or_null<NamespaceDecl>(D);
5373}
5374
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005375/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5376/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005377void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005378 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5379 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005380 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005381 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005382 if (Namespc->hasAttr<VisibilityAttr>())
5383 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005384}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005385
John McCall384aff82010-08-25 07:42:41 +00005386CXXRecordDecl *Sema::getStdBadAlloc() const {
5387 return cast_or_null<CXXRecordDecl>(
5388 StdBadAlloc.get(Context.getExternalSource()));
5389}
5390
5391NamespaceDecl *Sema::getStdNamespace() const {
5392 return cast_or_null<NamespaceDecl>(
5393 StdNamespace.get(Context.getExternalSource()));
5394}
5395
Douglas Gregor66992202010-06-29 17:53:46 +00005396/// \brief Retrieve the special "std" namespace, which may require us to
5397/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005398NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005399 if (!StdNamespace) {
5400 // The "std" namespace has not yet been defined, so build one implicitly.
5401 StdNamespace = NamespaceDecl::Create(Context,
5402 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005403 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00005404 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005405 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005406 }
5407
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005408 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005409}
5410
Douglas Gregor9172aa62011-03-26 22:25:30 +00005411/// \brief Determine whether a using statement is in a context where it will be
5412/// apply in all contexts.
5413static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5414 switch (CurContext->getDeclKind()) {
5415 case Decl::TranslationUnit:
5416 return true;
5417 case Decl::LinkageSpec:
5418 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5419 default:
5420 return false;
5421 }
5422}
5423
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005424static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5425 CXXScopeSpec &SS,
5426 SourceLocation IdentLoc,
5427 IdentifierInfo *Ident) {
5428 R.clear();
5429 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5430 R.getLookupKind(), Sc, &SS, NULL,
5431 false, S.CTC_NoKeywords, NULL)) {
5432 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5433 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5434 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5435 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5436 if (DeclContext *DC = S.computeDeclContext(SS, false))
5437 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5438 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5439 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5440 else
5441 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5442 << Ident << CorrectedQuotedStr
5443 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5444
5445 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5446 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5447
5448 Ident = Corrected.getCorrectionAsIdentifierInfo();
5449 R.addDecl(Corrected.getCorrectionDecl());
5450 return true;
5451 }
5452 R.setLookupName(Ident);
5453 }
5454 return false;
5455}
5456
John McCalld226f652010-08-21 09:40:31 +00005457Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005458 SourceLocation UsingLoc,
5459 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005460 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005461 SourceLocation IdentLoc,
5462 IdentifierInfo *NamespcName,
5463 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005464 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5465 assert(NamespcName && "Invalid NamespcName.");
5466 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005467
5468 // This can only happen along a recovery path.
5469 while (S->getFlags() & Scope::TemplateParamScope)
5470 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005471 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005472
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005473 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005474 NestedNameSpecifier *Qualifier = 0;
5475 if (SS.isSet())
5476 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5477
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005478 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005479 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5480 LookupParsedName(R, S, &SS);
5481 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005482 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005483
Douglas Gregor66992202010-06-29 17:53:46 +00005484 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005485 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005486 // Allow "using namespace std;" or "using namespace ::std;" even if
5487 // "std" hasn't been defined yet, for GCC compatibility.
5488 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5489 NamespcName->isStr("std")) {
5490 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005491 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005492 R.resolveKind();
5493 }
5494 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005495 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005496 }
5497
John McCallf36e02d2009-10-09 21:13:30 +00005498 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005499 NamedDecl *Named = R.getFoundDecl();
5500 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5501 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005502 // C++ [namespace.udir]p1:
5503 // A using-directive specifies that the names in the nominated
5504 // namespace can be used in the scope in which the
5505 // using-directive appears after the using-directive. During
5506 // unqualified name lookup (3.4.1), the names appear as if they
5507 // were declared in the nearest enclosing namespace which
5508 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005509 // namespace. [Note: in this context, "contains" means "contains
5510 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005511
5512 // Find enclosing context containing both using-directive and
5513 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005514 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005515 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5516 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5517 CommonAncestor = CommonAncestor->getParent();
5518
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005519 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005520 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005521 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005522
Douglas Gregor9172aa62011-03-26 22:25:30 +00005523 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005524 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005525 Diag(IdentLoc, diag::warn_using_directive_in_header);
5526 }
5527
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005528 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005529 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005530 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005531 }
5532
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005533 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005534 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005535}
5536
5537void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5538 // If scope has associated entity, then using directive is at namespace
5539 // or translation unit scope. We add UsingDirectiveDecls, into
5540 // it's lookup structure.
5541 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005542 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005543 else
5544 // Otherwise it is block-sope. using-directives will affect lookup
5545 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005546 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005547}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005548
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005549
John McCalld226f652010-08-21 09:40:31 +00005550Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005551 AccessSpecifier AS,
5552 bool HasUsingKeyword,
5553 SourceLocation UsingLoc,
5554 CXXScopeSpec &SS,
5555 UnqualifiedId &Name,
5556 AttributeList *AttrList,
5557 bool IsTypeName,
5558 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005559 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005560
Douglas Gregor12c118a2009-11-04 16:30:06 +00005561 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005562 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005563 case UnqualifiedId::IK_Identifier:
5564 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005565 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005566 case UnqualifiedId::IK_ConversionFunctionId:
5567 break;
5568
5569 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005570 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005571 // C++0x inherited constructors.
5572 if (getLangOptions().CPlusPlus0x) break;
5573
Douglas Gregor12c118a2009-11-04 16:30:06 +00005574 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5575 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005576 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005577
5578 case UnqualifiedId::IK_DestructorName:
5579 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5580 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005581 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005582
5583 case UnqualifiedId::IK_TemplateId:
5584 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5585 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005586 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005587 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005588
5589 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5590 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005591 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005592 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005593
John McCall60fa3cf2009-12-11 02:10:03 +00005594 // Warn about using declarations.
5595 // TODO: store that the declaration was written without 'using' and
5596 // talk about access decls instead of using decls in the
5597 // diagnostics.
5598 if (!HasUsingKeyword) {
5599 UsingLoc = Name.getSourceRange().getBegin();
5600
5601 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005602 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005603 }
5604
Douglas Gregor56c04582010-12-16 00:46:58 +00005605 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5606 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5607 return 0;
5608
John McCall9488ea12009-11-17 05:59:44 +00005609 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005610 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005611 /* IsInstantiation */ false,
5612 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005613 if (UD)
5614 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005615
John McCalld226f652010-08-21 09:40:31 +00005616 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005617}
5618
Douglas Gregor09acc982010-07-07 23:08:52 +00005619/// \brief Determine whether a using declaration considers the given
5620/// declarations as "equivalent", e.g., if they are redeclarations of
5621/// the same entity or are both typedefs of the same type.
5622static bool
5623IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5624 bool &SuppressRedeclaration) {
5625 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5626 SuppressRedeclaration = false;
5627 return true;
5628 }
5629
Richard Smith162e1c12011-04-15 14:24:37 +00005630 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5631 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005632 SuppressRedeclaration = true;
5633 return Context.hasSameType(TD1->getUnderlyingType(),
5634 TD2->getUnderlyingType());
5635 }
5636
5637 return false;
5638}
5639
5640
John McCall9f54ad42009-12-10 09:41:52 +00005641/// Determines whether to create a using shadow decl for a particular
5642/// decl, given the set of decls existing prior to this using lookup.
5643bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5644 const LookupResult &Previous) {
5645 // Diagnose finding a decl which is not from a base class of the
5646 // current class. We do this now because there are cases where this
5647 // function will silently decide not to build a shadow decl, which
5648 // will pre-empt further diagnostics.
5649 //
5650 // We don't need to do this in C++0x because we do the check once on
5651 // the qualifier.
5652 //
5653 // FIXME: diagnose the following if we care enough:
5654 // struct A { int foo; };
5655 // struct B : A { using A::foo; };
5656 // template <class T> struct C : A {};
5657 // template <class T> struct D : C<T> { using B::foo; } // <---
5658 // This is invalid (during instantiation) in C++03 because B::foo
5659 // resolves to the using decl in B, which is not a base class of D<T>.
5660 // We can't diagnose it immediately because C<T> is an unknown
5661 // specialization. The UsingShadowDecl in D<T> then points directly
5662 // to A::foo, which will look well-formed when we instantiate.
5663 // The right solution is to not collapse the shadow-decl chain.
5664 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5665 DeclContext *OrigDC = Orig->getDeclContext();
5666
5667 // Handle enums and anonymous structs.
5668 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5669 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5670 while (OrigRec->isAnonymousStructOrUnion())
5671 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5672
5673 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5674 if (OrigDC == CurContext) {
5675 Diag(Using->getLocation(),
5676 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005677 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005678 Diag(Orig->getLocation(), diag::note_using_decl_target);
5679 return true;
5680 }
5681
Douglas Gregordc355712011-02-25 00:36:19 +00005682 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005683 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005684 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005685 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005686 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005687 Diag(Orig->getLocation(), diag::note_using_decl_target);
5688 return true;
5689 }
5690 }
5691
5692 if (Previous.empty()) return false;
5693
5694 NamedDecl *Target = Orig;
5695 if (isa<UsingShadowDecl>(Target))
5696 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5697
John McCalld7533ec2009-12-11 02:33:26 +00005698 // If the target happens to be one of the previous declarations, we
5699 // don't have a conflict.
5700 //
5701 // FIXME: but we might be increasing its access, in which case we
5702 // should redeclare it.
5703 NamedDecl *NonTag = 0, *Tag = 0;
5704 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5705 I != E; ++I) {
5706 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005707 bool Result;
5708 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5709 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005710
5711 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5712 }
5713
John McCall9f54ad42009-12-10 09:41:52 +00005714 if (Target->isFunctionOrFunctionTemplate()) {
5715 FunctionDecl *FD;
5716 if (isa<FunctionTemplateDecl>(Target))
5717 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5718 else
5719 FD = cast<FunctionDecl>(Target);
5720
5721 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005722 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005723 case Ovl_Overload:
5724 return false;
5725
5726 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005727 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005728 break;
5729
5730 // We found a decl with the exact signature.
5731 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005732 // If we're in a record, we want to hide the target, so we
5733 // return true (without a diagnostic) to tell the caller not to
5734 // build a shadow decl.
5735 if (CurContext->isRecord())
5736 return true;
5737
5738 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005739 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005740 break;
5741 }
5742
5743 Diag(Target->getLocation(), diag::note_using_decl_target);
5744 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5745 return true;
5746 }
5747
5748 // Target is not a function.
5749
John McCall9f54ad42009-12-10 09:41:52 +00005750 if (isa<TagDecl>(Target)) {
5751 // No conflict between a tag and a non-tag.
5752 if (!Tag) return false;
5753
John McCall41ce66f2009-12-10 19:51:03 +00005754 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005755 Diag(Target->getLocation(), diag::note_using_decl_target);
5756 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5757 return true;
5758 }
5759
5760 // No conflict between a tag and a non-tag.
5761 if (!NonTag) return false;
5762
John McCall41ce66f2009-12-10 19:51:03 +00005763 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005764 Diag(Target->getLocation(), diag::note_using_decl_target);
5765 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5766 return true;
5767}
5768
John McCall9488ea12009-11-17 05:59:44 +00005769/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005770UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005771 UsingDecl *UD,
5772 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005773
5774 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005775 NamedDecl *Target = Orig;
5776 if (isa<UsingShadowDecl>(Target)) {
5777 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5778 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005779 }
5780
5781 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005782 = UsingShadowDecl::Create(Context, CurContext,
5783 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005784 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005785
5786 Shadow->setAccess(UD->getAccess());
5787 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5788 Shadow->setInvalidDecl();
5789
John McCall9488ea12009-11-17 05:59:44 +00005790 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005791 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005792 else
John McCall604e7f12009-12-08 07:46:18 +00005793 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005794
John McCall604e7f12009-12-08 07:46:18 +00005795
John McCall9f54ad42009-12-10 09:41:52 +00005796 return Shadow;
5797}
John McCall604e7f12009-12-08 07:46:18 +00005798
John McCall9f54ad42009-12-10 09:41:52 +00005799/// Hides a using shadow declaration. This is required by the current
5800/// using-decl implementation when a resolvable using declaration in a
5801/// class is followed by a declaration which would hide or override
5802/// one or more of the using decl's targets; for example:
5803///
5804/// struct Base { void foo(int); };
5805/// struct Derived : Base {
5806/// using Base::foo;
5807/// void foo(int);
5808/// };
5809///
5810/// The governing language is C++03 [namespace.udecl]p12:
5811///
5812/// When a using-declaration brings names from a base class into a
5813/// derived class scope, member functions in the derived class
5814/// override and/or hide member functions with the same name and
5815/// parameter types in a base class (rather than conflicting).
5816///
5817/// There are two ways to implement this:
5818/// (1) optimistically create shadow decls when they're not hidden
5819/// by existing declarations, or
5820/// (2) don't create any shadow decls (or at least don't make them
5821/// visible) until we've fully parsed/instantiated the class.
5822/// The problem with (1) is that we might have to retroactively remove
5823/// a shadow decl, which requires several O(n) operations because the
5824/// decl structures are (very reasonably) not designed for removal.
5825/// (2) avoids this but is very fiddly and phase-dependent.
5826void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005827 if (Shadow->getDeclName().getNameKind() ==
5828 DeclarationName::CXXConversionFunctionName)
5829 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5830
John McCall9f54ad42009-12-10 09:41:52 +00005831 // Remove it from the DeclContext...
5832 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005833
John McCall9f54ad42009-12-10 09:41:52 +00005834 // ...and the scope, if applicable...
5835 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005836 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005837 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005838 }
5839
John McCall9f54ad42009-12-10 09:41:52 +00005840 // ...and the using decl.
5841 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5842
5843 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005844 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005845}
5846
John McCall7ba107a2009-11-18 02:36:19 +00005847/// Builds a using declaration.
5848///
5849/// \param IsInstantiation - Whether this call arises from an
5850/// instantiation of an unresolved using declaration. We treat
5851/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005852NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5853 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005854 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005855 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005856 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005857 bool IsInstantiation,
5858 bool IsTypeName,
5859 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005860 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005861 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005862 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005863
Anders Carlsson550b14b2009-08-28 05:49:21 +00005864 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005865
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005866 if (SS.isEmpty()) {
5867 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005868 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005869 }
Mike Stump1eb44332009-09-09 15:08:12 +00005870
John McCall9f54ad42009-12-10 09:41:52 +00005871 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005872 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005873 ForRedeclaration);
5874 Previous.setHideTags(false);
5875 if (S) {
5876 LookupName(Previous, S);
5877
5878 // It is really dumb that we have to do this.
5879 LookupResult::Filter F = Previous.makeFilter();
5880 while (F.hasNext()) {
5881 NamedDecl *D = F.next();
5882 if (!isDeclInScope(D, CurContext, S))
5883 F.erase();
5884 }
5885 F.done();
5886 } else {
5887 assert(IsInstantiation && "no scope in non-instantiation");
5888 assert(CurContext->isRecord() && "scope not record in instantiation");
5889 LookupQualifiedName(Previous, CurContext);
5890 }
5891
John McCall9f54ad42009-12-10 09:41:52 +00005892 // Check for invalid redeclarations.
5893 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5894 return 0;
5895
5896 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005897 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5898 return 0;
5899
John McCallaf8e6ed2009-11-12 03:15:40 +00005900 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005901 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005902 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005903 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005904 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005905 // FIXME: not all declaration name kinds are legal here
5906 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5907 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005908 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005909 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005910 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005911 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5912 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005913 }
John McCalled976492009-12-04 22:46:56 +00005914 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005915 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5916 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005917 }
John McCalled976492009-12-04 22:46:56 +00005918 D->setAccess(AS);
5919 CurContext->addDecl(D);
5920
5921 if (!LookupContext) return D;
5922 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005923
John McCall77bb1aa2010-05-01 00:40:08 +00005924 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005925 UD->setInvalidDecl();
5926 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005927 }
5928
Sebastian Redlf677ea32011-02-05 19:23:19 +00005929 // Constructor inheriting using decls get special treatment.
5930 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005931 if (CheckInheritedConstructorUsingDecl(UD))
5932 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005933 return UD;
5934 }
5935
5936 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005937
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005938 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005939 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005940
John McCall604e7f12009-12-08 07:46:18 +00005941 // Unlike most lookups, we don't always want to hide tag
5942 // declarations: tag names are visible through the using declaration
5943 // even if hidden by ordinary names, *except* in a dependent context
5944 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005945 if (!IsInstantiation)
5946 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005947
John McCalla24dc2e2009-11-17 02:14:36 +00005948 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005949
John McCallf36e02d2009-10-09 21:13:30 +00005950 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005951 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005952 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005953 UD->setInvalidDecl();
5954 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005955 }
5956
John McCalled976492009-12-04 22:46:56 +00005957 if (R.isAmbiguous()) {
5958 UD->setInvalidDecl();
5959 return UD;
5960 }
Mike Stump1eb44332009-09-09 15:08:12 +00005961
John McCall7ba107a2009-11-18 02:36:19 +00005962 if (IsTypeName) {
5963 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005964 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005965 Diag(IdentLoc, diag::err_using_typename_non_type);
5966 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5967 Diag((*I)->getUnderlyingDecl()->getLocation(),
5968 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005969 UD->setInvalidDecl();
5970 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005971 }
5972 } else {
5973 // If we asked for a non-typename and we got a type, error out,
5974 // but only if this is an instantiation of an unresolved using
5975 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005976 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005977 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5978 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005979 UD->setInvalidDecl();
5980 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005981 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005982 }
5983
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005984 // C++0x N2914 [namespace.udecl]p6:
5985 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005986 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005987 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5988 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005989 UD->setInvalidDecl();
5990 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005991 }
Mike Stump1eb44332009-09-09 15:08:12 +00005992
John McCall9f54ad42009-12-10 09:41:52 +00005993 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5994 if (!CheckUsingShadowDecl(UD, *I, Previous))
5995 BuildUsingShadowDecl(S, UD, *I);
5996 }
John McCall9488ea12009-11-17 05:59:44 +00005997
5998 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005999}
6000
Sebastian Redlf677ea32011-02-05 19:23:19 +00006001/// Additional checks for a using declaration referring to a constructor name.
6002bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6003 if (UD->isTypeName()) {
6004 // FIXME: Cannot specify typename when specifying constructor
6005 return true;
6006 }
6007
Douglas Gregordc355712011-02-25 00:36:19 +00006008 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006009 assert(SourceType &&
6010 "Using decl naming constructor doesn't have type in scope spec.");
6011 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6012
6013 // Check whether the named type is a direct base class.
6014 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6015 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6016 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6017 BaseIt != BaseE; ++BaseIt) {
6018 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6019 if (CanonicalSourceType == BaseType)
6020 break;
6021 }
6022
6023 if (BaseIt == BaseE) {
6024 // Did not find SourceType in the bases.
6025 Diag(UD->getUsingLocation(),
6026 diag::err_using_decl_constructor_not_in_direct_base)
6027 << UD->getNameInfo().getSourceRange()
6028 << QualType(SourceType, 0) << TargetClass;
6029 return true;
6030 }
6031
6032 BaseIt->setInheritConstructors();
6033
6034 return false;
6035}
6036
John McCall9f54ad42009-12-10 09:41:52 +00006037/// Checks that the given using declaration is not an invalid
6038/// redeclaration. Note that this is checking only for the using decl
6039/// itself, not for any ill-formedness among the UsingShadowDecls.
6040bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6041 bool isTypeName,
6042 const CXXScopeSpec &SS,
6043 SourceLocation NameLoc,
6044 const LookupResult &Prev) {
6045 // C++03 [namespace.udecl]p8:
6046 // C++0x [namespace.udecl]p10:
6047 // A using-declaration is a declaration and can therefore be used
6048 // repeatedly where (and only where) multiple declarations are
6049 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006050 //
John McCall8a726212010-11-29 18:01:58 +00006051 // That's in non-member contexts.
6052 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006053 return false;
6054
6055 NestedNameSpecifier *Qual
6056 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6057
6058 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6059 NamedDecl *D = *I;
6060
6061 bool DTypename;
6062 NestedNameSpecifier *DQual;
6063 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6064 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006065 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006066 } else if (UnresolvedUsingValueDecl *UD
6067 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6068 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006069 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006070 } else if (UnresolvedUsingTypenameDecl *UD
6071 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6072 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006073 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006074 } else continue;
6075
6076 // using decls differ if one says 'typename' and the other doesn't.
6077 // FIXME: non-dependent using decls?
6078 if (isTypeName != DTypename) continue;
6079
6080 // using decls differ if they name different scopes (but note that
6081 // template instantiation can cause this check to trigger when it
6082 // didn't before instantiation).
6083 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6084 Context.getCanonicalNestedNameSpecifier(DQual))
6085 continue;
6086
6087 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006088 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006089 return true;
6090 }
6091
6092 return false;
6093}
6094
John McCall604e7f12009-12-08 07:46:18 +00006095
John McCalled976492009-12-04 22:46:56 +00006096/// Checks that the given nested-name qualifier used in a using decl
6097/// in the current context is appropriately related to the current
6098/// scope. If an error is found, diagnoses it and returns true.
6099bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6100 const CXXScopeSpec &SS,
6101 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006102 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006103
John McCall604e7f12009-12-08 07:46:18 +00006104 if (!CurContext->isRecord()) {
6105 // C++03 [namespace.udecl]p3:
6106 // C++0x [namespace.udecl]p8:
6107 // A using-declaration for a class member shall be a member-declaration.
6108
6109 // If we weren't able to compute a valid scope, it must be a
6110 // dependent class scope.
6111 if (!NamedContext || NamedContext->isRecord()) {
6112 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6113 << SS.getRange();
6114 return true;
6115 }
6116
6117 // Otherwise, everything is known to be fine.
6118 return false;
6119 }
6120
6121 // The current scope is a record.
6122
6123 // If the named context is dependent, we can't decide much.
6124 if (!NamedContext) {
6125 // FIXME: in C++0x, we can diagnose if we can prove that the
6126 // nested-name-specifier does not refer to a base class, which is
6127 // still possible in some cases.
6128
6129 // Otherwise we have to conservatively report that things might be
6130 // okay.
6131 return false;
6132 }
6133
6134 if (!NamedContext->isRecord()) {
6135 // Ideally this would point at the last name in the specifier,
6136 // but we don't have that level of source info.
6137 Diag(SS.getRange().getBegin(),
6138 diag::err_using_decl_nested_name_specifier_is_not_class)
6139 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6140 return true;
6141 }
6142
Douglas Gregor6fb07292010-12-21 07:41:49 +00006143 if (!NamedContext->isDependentContext() &&
6144 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6145 return true;
6146
John McCall604e7f12009-12-08 07:46:18 +00006147 if (getLangOptions().CPlusPlus0x) {
6148 // C++0x [namespace.udecl]p3:
6149 // In a using-declaration used as a member-declaration, the
6150 // nested-name-specifier shall name a base class of the class
6151 // being defined.
6152
6153 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6154 cast<CXXRecordDecl>(NamedContext))) {
6155 if (CurContext == NamedContext) {
6156 Diag(NameLoc,
6157 diag::err_using_decl_nested_name_specifier_is_current_class)
6158 << SS.getRange();
6159 return true;
6160 }
6161
6162 Diag(SS.getRange().getBegin(),
6163 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6164 << (NestedNameSpecifier*) SS.getScopeRep()
6165 << cast<CXXRecordDecl>(CurContext)
6166 << SS.getRange();
6167 return true;
6168 }
6169
6170 return false;
6171 }
6172
6173 // C++03 [namespace.udecl]p4:
6174 // A using-declaration used as a member-declaration shall refer
6175 // to a member of a base class of the class being defined [etc.].
6176
6177 // Salient point: SS doesn't have to name a base class as long as
6178 // lookup only finds members from base classes. Therefore we can
6179 // diagnose here only if we can prove that that can't happen,
6180 // i.e. if the class hierarchies provably don't intersect.
6181
6182 // TODO: it would be nice if "definitely valid" results were cached
6183 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6184 // need to be repeated.
6185
6186 struct UserData {
6187 llvm::DenseSet<const CXXRecordDecl*> Bases;
6188
6189 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6190 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6191 Data->Bases.insert(Base);
6192 return true;
6193 }
6194
6195 bool hasDependentBases(const CXXRecordDecl *Class) {
6196 return !Class->forallBases(collect, this);
6197 }
6198
6199 /// Returns true if the base is dependent or is one of the
6200 /// accumulated base classes.
6201 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6202 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6203 return !Data->Bases.count(Base);
6204 }
6205
6206 bool mightShareBases(const CXXRecordDecl *Class) {
6207 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6208 }
6209 };
6210
6211 UserData Data;
6212
6213 // Returns false if we find a dependent base.
6214 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6215 return false;
6216
6217 // Returns false if the class has a dependent base or if it or one
6218 // of its bases is present in the base set of the current context.
6219 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6220 return false;
6221
6222 Diag(SS.getRange().getBegin(),
6223 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6224 << (NestedNameSpecifier*) SS.getScopeRep()
6225 << cast<CXXRecordDecl>(CurContext)
6226 << SS.getRange();
6227
6228 return true;
John McCalled976492009-12-04 22:46:56 +00006229}
6230
Richard Smith162e1c12011-04-15 14:24:37 +00006231Decl *Sema::ActOnAliasDeclaration(Scope *S,
6232 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006233 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006234 SourceLocation UsingLoc,
6235 UnqualifiedId &Name,
6236 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006237 // Skip up to the relevant declaration scope.
6238 while (S->getFlags() & Scope::TemplateParamScope)
6239 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006240 assert((S->getFlags() & Scope::DeclScope) &&
6241 "got alias-declaration outside of declaration scope");
6242
6243 if (Type.isInvalid())
6244 return 0;
6245
6246 bool Invalid = false;
6247 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6248 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006249 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006250
6251 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6252 return 0;
6253
6254 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006255 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006256 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006257 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6258 TInfo->getTypeLoc().getBeginLoc());
6259 }
Richard Smith162e1c12011-04-15 14:24:37 +00006260
6261 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6262 LookupName(Previous, S);
6263
6264 // Warn about shadowing the name of a template parameter.
6265 if (Previous.isSingleResult() &&
6266 Previous.getFoundDecl()->isTemplateParameter()) {
6267 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6268 Previous.getFoundDecl()))
6269 Invalid = true;
6270 Previous.clear();
6271 }
6272
6273 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6274 "name in alias declaration must be an identifier");
6275 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6276 Name.StartLocation,
6277 Name.Identifier, TInfo);
6278
6279 NewTD->setAccess(AS);
6280
6281 if (Invalid)
6282 NewTD->setInvalidDecl();
6283
Richard Smith3e4c6c42011-05-05 21:57:07 +00006284 CheckTypedefForVariablyModifiedType(S, NewTD);
6285 Invalid |= NewTD->isInvalidDecl();
6286
Richard Smith162e1c12011-04-15 14:24:37 +00006287 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006288
6289 NamedDecl *NewND;
6290 if (TemplateParamLists.size()) {
6291 TypeAliasTemplateDecl *OldDecl = 0;
6292 TemplateParameterList *OldTemplateParams = 0;
6293
6294 if (TemplateParamLists.size() != 1) {
6295 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6296 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6297 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6298 }
6299 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6300
6301 // Only consider previous declarations in the same scope.
6302 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6303 /*ExplicitInstantiationOrSpecialization*/false);
6304 if (!Previous.empty()) {
6305 Redeclaration = true;
6306
6307 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6308 if (!OldDecl && !Invalid) {
6309 Diag(UsingLoc, diag::err_redefinition_different_kind)
6310 << Name.Identifier;
6311
6312 NamedDecl *OldD = Previous.getRepresentativeDecl();
6313 if (OldD->getLocation().isValid())
6314 Diag(OldD->getLocation(), diag::note_previous_definition);
6315
6316 Invalid = true;
6317 }
6318
6319 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6320 if (TemplateParameterListsAreEqual(TemplateParams,
6321 OldDecl->getTemplateParameters(),
6322 /*Complain=*/true,
6323 TPL_TemplateMatch))
6324 OldTemplateParams = OldDecl->getTemplateParameters();
6325 else
6326 Invalid = true;
6327
6328 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6329 if (!Invalid &&
6330 !Context.hasSameType(OldTD->getUnderlyingType(),
6331 NewTD->getUnderlyingType())) {
6332 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6333 // but we can't reasonably accept it.
6334 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6335 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6336 if (OldTD->getLocation().isValid())
6337 Diag(OldTD->getLocation(), diag::note_previous_definition);
6338 Invalid = true;
6339 }
6340 }
6341 }
6342
6343 // Merge any previous default template arguments into our parameters,
6344 // and check the parameter list.
6345 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6346 TPC_TypeAliasTemplate))
6347 return 0;
6348
6349 TypeAliasTemplateDecl *NewDecl =
6350 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6351 Name.Identifier, TemplateParams,
6352 NewTD);
6353
6354 NewDecl->setAccess(AS);
6355
6356 if (Invalid)
6357 NewDecl->setInvalidDecl();
6358 else if (OldDecl)
6359 NewDecl->setPreviousDeclaration(OldDecl);
6360
6361 NewND = NewDecl;
6362 } else {
6363 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6364 NewND = NewTD;
6365 }
Richard Smith162e1c12011-04-15 14:24:37 +00006366
6367 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006368 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006369
Richard Smith3e4c6c42011-05-05 21:57:07 +00006370 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006371}
6372
John McCalld226f652010-08-21 09:40:31 +00006373Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006374 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006375 SourceLocation AliasLoc,
6376 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006377 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006378 SourceLocation IdentLoc,
6379 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006380
Anders Carlsson81c85c42009-03-28 23:53:49 +00006381 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006382 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6383 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006384
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006385 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006386 NamedDecl *PrevDecl
6387 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6388 ForRedeclaration);
6389 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6390 PrevDecl = 0;
6391
6392 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006393 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006394 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006395 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006396 // FIXME: At some point, we'll want to create the (redundant)
6397 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006398 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006399 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006400 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006401 }
Mike Stump1eb44332009-09-09 15:08:12 +00006402
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006403 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6404 diag::err_redefinition_different_kind;
6405 Diag(AliasLoc, DiagID) << Alias;
6406 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006407 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006408 }
6409
John McCalla24dc2e2009-11-17 02:14:36 +00006410 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006411 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006412
John McCallf36e02d2009-10-09 21:13:30 +00006413 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006414 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006415 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006416 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006417 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006418 }
Mike Stump1eb44332009-09-09 15:08:12 +00006419
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006420 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006421 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006422 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006423 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006424
John McCall3dbd3d52010-02-16 06:53:13 +00006425 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006426 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006427}
6428
Douglas Gregor39957dc2010-05-01 15:04:51 +00006429namespace {
6430 /// \brief Scoped object used to handle the state changes required in Sema
6431 /// to implicitly define the body of a C++ member function;
6432 class ImplicitlyDefinedFunctionScope {
6433 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006434 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006435
6436 public:
6437 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006438 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006439 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006440 S.PushFunctionScope();
6441 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6442 }
6443
6444 ~ImplicitlyDefinedFunctionScope() {
6445 S.PopExpressionEvaluationContext();
6446 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006447 }
6448 };
6449}
6450
Sean Hunt001cad92011-05-10 00:49:42 +00006451Sema::ImplicitExceptionSpecification
6452Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006453 // C++ [except.spec]p14:
6454 // An implicitly declared special member function (Clause 12) shall have an
6455 // exception-specification. [...]
6456 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006457 if (ClassDecl->isInvalidDecl())
6458 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006459
Sebastian Redl60618fa2011-03-12 11:50:43 +00006460 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006461 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6462 BEnd = ClassDecl->bases_end();
6463 B != BEnd; ++B) {
6464 if (B->isVirtual()) // Handled below.
6465 continue;
6466
Douglas Gregor18274032010-07-03 00:47:00 +00006467 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6468 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006469 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6470 // If this is a deleted function, add it anyway. This might be conformant
6471 // with the standard. This might not. I'm not sure. It might not matter.
6472 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006473 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006474 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006475 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006476
6477 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006478 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6479 BEnd = ClassDecl->vbases_end();
6480 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006481 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6482 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006483 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6484 // If this is a deleted function, add it anyway. This might be conformant
6485 // with the standard. This might not. I'm not sure. It might not matter.
6486 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006487 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006488 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006489 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006490
6491 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006492 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6493 FEnd = ClassDecl->field_end();
6494 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006495 if (F->hasInClassInitializer()) {
6496 if (Expr *E = F->getInClassInitializer())
6497 ExceptSpec.CalledExpr(E);
6498 else if (!F->isInvalidDecl())
6499 ExceptSpec.SetDelayed();
6500 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006501 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006502 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6503 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6504 // If this is a deleted function, add it anyway. This might be conformant
6505 // with the standard. This might not. I'm not sure. It might not matter.
6506 // In particular, the problem is that this function never gets called. It
6507 // might just be ill-formed because this function attempts to refer to
6508 // a deleted function here.
6509 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006510 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006511 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006512 }
John McCalle23cf432010-12-14 08:05:40 +00006513
Sean Hunt001cad92011-05-10 00:49:42 +00006514 return ExceptSpec;
6515}
6516
6517CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6518 CXXRecordDecl *ClassDecl) {
6519 // C++ [class.ctor]p5:
6520 // A default constructor for a class X is a constructor of class X
6521 // that can be called without an argument. If there is no
6522 // user-declared constructor for class X, a default constructor is
6523 // implicitly declared. An implicitly-declared default constructor
6524 // is an inline public member of its class.
6525 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6526 "Should not build implicit default constructor!");
6527
6528 ImplicitExceptionSpecification Spec =
6529 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6530 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006531
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006532 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006533 CanQualType ClassType
6534 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006535 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006536 DeclarationName Name
6537 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006538 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006539 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006540 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006541 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006542 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006543 /*TInfo=*/0,
6544 /*isExplicit=*/false,
6545 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006546 /*isImplicitlyDeclared=*/true,
6547 // FIXME: apply the rules for definitions here
6548 /*isConstexpr=*/false);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006549 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006550 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006551 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006552 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006553
6554 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006555 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6556
Douglas Gregor23c94db2010-07-02 17:43:08 +00006557 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006558 PushOnScopeChains(DefaultCon, S, false);
6559 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006560
6561 if (ShouldDeleteDefaultConstructor(DefaultCon))
6562 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006563
Douglas Gregor32df23e2010-07-01 22:02:46 +00006564 return DefaultCon;
6565}
6566
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006567void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6568 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006569 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006570 !Constructor->doesThisDeclarationHaveABody() &&
6571 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006572 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006573
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006574 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006575 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006576
Douglas Gregor39957dc2010-05-01 15:04:51 +00006577 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006578 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006579 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006580 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006581 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006582 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006583 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006584 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006585 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006586
6587 SourceLocation Loc = Constructor->getLocation();
6588 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6589
6590 Constructor->setUsed();
6591 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006592
6593 if (ASTMutationListener *L = getASTMutationListener()) {
6594 L->CompletedImplicitDefinition(Constructor);
6595 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006596}
6597
Richard Smith7a614d82011-06-11 17:19:42 +00006598/// Get any existing defaulted default constructor for the given class. Do not
6599/// implicitly define one if it does not exist.
6600static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6601 CXXRecordDecl *D) {
6602 ASTContext &Context = Self.Context;
6603 QualType ClassType = Context.getTypeDeclType(D);
6604 DeclarationName ConstructorName
6605 = Context.DeclarationNames.getCXXConstructorName(
6606 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6607
6608 DeclContext::lookup_const_iterator Con, ConEnd;
6609 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6610 Con != ConEnd; ++Con) {
6611 // A function template cannot be defaulted.
6612 if (isa<FunctionTemplateDecl>(*Con))
6613 continue;
6614
6615 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6616 if (Constructor->isDefaultConstructor())
6617 return Constructor->isDefaulted() ? Constructor : 0;
6618 }
6619 return 0;
6620}
6621
6622void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6623 if (!D) return;
6624 AdjustDeclIfTemplate(D);
6625
6626 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6627 CXXConstructorDecl *CtorDecl
6628 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6629
6630 if (!CtorDecl) return;
6631
6632 // Compute the exception specification for the default constructor.
6633 const FunctionProtoType *CtorTy =
6634 CtorDecl->getType()->castAs<FunctionProtoType>();
6635 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6636 ImplicitExceptionSpecification Spec =
6637 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6638 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6639 assert(EPI.ExceptionSpecType != EST_Delayed);
6640
6641 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6642 }
6643
6644 // If the default constructor is explicitly defaulted, checking the exception
6645 // specification is deferred until now.
6646 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6647 !ClassDecl->isDependentType())
6648 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6649}
6650
Sebastian Redlf677ea32011-02-05 19:23:19 +00006651void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6652 // We start with an initial pass over the base classes to collect those that
6653 // inherit constructors from. If there are none, we can forgo all further
6654 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006655 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006656 BasesVector BasesToInheritFrom;
6657 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6658 BaseE = ClassDecl->bases_end();
6659 BaseIt != BaseE; ++BaseIt) {
6660 if (BaseIt->getInheritConstructors()) {
6661 QualType Base = BaseIt->getType();
6662 if (Base->isDependentType()) {
6663 // If we inherit constructors from anything that is dependent, just
6664 // abort processing altogether. We'll get another chance for the
6665 // instantiations.
6666 return;
6667 }
6668 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6669 }
6670 }
6671 if (BasesToInheritFrom.empty())
6672 return;
6673
6674 // Now collect the constructors that we already have in the current class.
6675 // Those take precedence over inherited constructors.
6676 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6677 // unless there is a user-declared constructor with the same signature in
6678 // the class where the using-declaration appears.
6679 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6680 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6681 CtorE = ClassDecl->ctor_end();
6682 CtorIt != CtorE; ++CtorIt) {
6683 ExistingConstructors.insert(
6684 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6685 }
6686
6687 Scope *S = getScopeForContext(ClassDecl);
6688 DeclarationName CreatedCtorName =
6689 Context.DeclarationNames.getCXXConstructorName(
6690 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6691
6692 // Now comes the true work.
6693 // First, we keep a map from constructor types to the base that introduced
6694 // them. Needed for finding conflicting constructors. We also keep the
6695 // actually inserted declarations in there, for pretty diagnostics.
6696 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6697 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6698 ConstructorToSourceMap InheritedConstructors;
6699 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6700 BaseE = BasesToInheritFrom.end();
6701 BaseIt != BaseE; ++BaseIt) {
6702 const RecordType *Base = *BaseIt;
6703 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6704 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6705 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6706 CtorE = BaseDecl->ctor_end();
6707 CtorIt != CtorE; ++CtorIt) {
6708 // Find the using declaration for inheriting this base's constructors.
6709 DeclarationName Name =
6710 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6711 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6712 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6713 SourceLocation UsingLoc = UD ? UD->getLocation() :
6714 ClassDecl->getLocation();
6715
6716 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6717 // from the class X named in the using-declaration consists of actual
6718 // constructors and notional constructors that result from the
6719 // transformation of defaulted parameters as follows:
6720 // - all non-template default constructors of X, and
6721 // - for each non-template constructor of X that has at least one
6722 // parameter with a default argument, the set of constructors that
6723 // results from omitting any ellipsis parameter specification and
6724 // successively omitting parameters with a default argument from the
6725 // end of the parameter-type-list.
6726 CXXConstructorDecl *BaseCtor = *CtorIt;
6727 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6728 const FunctionProtoType *BaseCtorType =
6729 BaseCtor->getType()->getAs<FunctionProtoType>();
6730
6731 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6732 maxParams = BaseCtor->getNumParams();
6733 params <= maxParams; ++params) {
6734 // Skip default constructors. They're never inherited.
6735 if (params == 0)
6736 continue;
6737 // Skip copy and move constructors for the same reason.
6738 if (CanBeCopyOrMove && params == 1)
6739 continue;
6740
6741 // Build up a function type for this particular constructor.
6742 // FIXME: The working paper does not consider that the exception spec
6743 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006744 // source. This code doesn't yet, either. When it does, this code will
6745 // need to be delayed until after exception specifications and in-class
6746 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006747 const Type *NewCtorType;
6748 if (params == maxParams)
6749 NewCtorType = BaseCtorType;
6750 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006751 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006752 for (unsigned i = 0; i < params; ++i) {
6753 Args.push_back(BaseCtorType->getArgType(i));
6754 }
6755 FunctionProtoType::ExtProtoInfo ExtInfo =
6756 BaseCtorType->getExtProtoInfo();
6757 ExtInfo.Variadic = false;
6758 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6759 Args.data(), params, ExtInfo)
6760 .getTypePtr();
6761 }
6762 const Type *CanonicalNewCtorType =
6763 Context.getCanonicalType(NewCtorType);
6764
6765 // Now that we have the type, first check if the class already has a
6766 // constructor with this signature.
6767 if (ExistingConstructors.count(CanonicalNewCtorType))
6768 continue;
6769
6770 // Then we check if we have already declared an inherited constructor
6771 // with this signature.
6772 std::pair<ConstructorToSourceMap::iterator, bool> result =
6773 InheritedConstructors.insert(std::make_pair(
6774 CanonicalNewCtorType,
6775 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6776 if (!result.second) {
6777 // Already in the map. If it came from a different class, that's an
6778 // error. Not if it's from the same.
6779 CanQualType PreviousBase = result.first->second.first;
6780 if (CanonicalBase != PreviousBase) {
6781 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6782 const CXXConstructorDecl *PrevBaseCtor =
6783 PrevCtor->getInheritedConstructor();
6784 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6785
6786 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6787 Diag(BaseCtor->getLocation(),
6788 diag::note_using_decl_constructor_conflict_current_ctor);
6789 Diag(PrevBaseCtor->getLocation(),
6790 diag::note_using_decl_constructor_conflict_previous_ctor);
6791 Diag(PrevCtor->getLocation(),
6792 diag::note_using_decl_constructor_conflict_previous_using);
6793 }
6794 continue;
6795 }
6796
6797 // OK, we're there, now add the constructor.
6798 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006799 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006800 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6801 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006802 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6803 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006804 /*ImplicitlyDeclared=*/true,
6805 // FIXME: Due to a defect in the standard, we treat inherited
6806 // constructors as constexpr even if that makes them ill-formed.
6807 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006808 NewCtor->setAccess(BaseCtor->getAccess());
6809
6810 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006811 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006812 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006813 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6814 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006815 /*IdentifierInfo=*/0,
6816 BaseCtorType->getArgType(i),
6817 /*TInfo=*/0, SC_None,
6818 SC_None, /*DefaultArg=*/0));
6819 }
6820 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6821 NewCtor->setInheritedConstructor(BaseCtor);
6822
6823 PushOnScopeChains(NewCtor, S, false);
6824 ClassDecl->addDecl(NewCtor);
6825 result.first->second.second = NewCtor;
6826 }
6827 }
6828 }
6829}
6830
Sean Huntcb45a0f2011-05-12 22:46:25 +00006831Sema::ImplicitExceptionSpecification
6832Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006833 // C++ [except.spec]p14:
6834 // An implicitly declared special member function (Clause 12) shall have
6835 // an exception-specification.
6836 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006837 if (ClassDecl->isInvalidDecl())
6838 return ExceptSpec;
6839
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006840 // Direct base-class destructors.
6841 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6842 BEnd = ClassDecl->bases_end();
6843 B != BEnd; ++B) {
6844 if (B->isVirtual()) // Handled below.
6845 continue;
6846
6847 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6848 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006849 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006850 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006851
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006852 // Virtual base-class destructors.
6853 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6854 BEnd = ClassDecl->vbases_end();
6855 B != BEnd; ++B) {
6856 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6857 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006858 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006859 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006860
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006861 // Field destructors.
6862 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6863 FEnd = ClassDecl->field_end();
6864 F != FEnd; ++F) {
6865 if (const RecordType *RecordTy
6866 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6867 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006868 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006869 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006870
Sean Huntcb45a0f2011-05-12 22:46:25 +00006871 return ExceptSpec;
6872}
6873
6874CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6875 // C++ [class.dtor]p2:
6876 // If a class has no user-declared destructor, a destructor is
6877 // declared implicitly. An implicitly-declared destructor is an
6878 // inline public member of its class.
6879
6880 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006881 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006882 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6883
Douglas Gregor4923aa22010-07-02 20:37:36 +00006884 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006885 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006886
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006887 CanQualType ClassType
6888 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006889 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006890 DeclarationName Name
6891 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006892 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006893 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006894 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6895 /*isInline=*/true,
6896 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006897 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006898 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006899 Destructor->setImplicit();
6900 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006901
6902 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006903 ++ASTContext::NumImplicitDestructorsDeclared;
6904
6905 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006906 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006907 PushOnScopeChains(Destructor, S, false);
6908 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006909
6910 // This could be uniqued if it ever proves significant.
6911 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006912
6913 if (ShouldDeleteDestructor(Destructor))
6914 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006915
6916 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006917
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006918 return Destructor;
6919}
6920
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006921void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006922 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006923 assert((Destructor->isDefaulted() &&
6924 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006925 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006926 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006927 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006928
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006929 if (Destructor->isInvalidDecl())
6930 return;
6931
Douglas Gregor39957dc2010-05-01 15:04:51 +00006932 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006933
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006934 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006935 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6936 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006937
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006938 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006939 Diag(CurrentLocation, diag::note_member_synthesized_at)
6940 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6941
6942 Destructor->setInvalidDecl();
6943 return;
6944 }
6945
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006946 SourceLocation Loc = Destructor->getLocation();
6947 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6948
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006949 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006950 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006951
6952 if (ASTMutationListener *L = getASTMutationListener()) {
6953 L->CompletedImplicitDefinition(Destructor);
6954 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006955}
6956
Sebastian Redl0ee33912011-05-19 05:13:44 +00006957void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6958 CXXDestructorDecl *destructor) {
6959 // C++11 [class.dtor]p3:
6960 // A declaration of a destructor that does not have an exception-
6961 // specification is implicitly considered to have the same exception-
6962 // specification as an implicit declaration.
6963 const FunctionProtoType *dtorType = destructor->getType()->
6964 getAs<FunctionProtoType>();
6965 if (dtorType->hasExceptionSpec())
6966 return;
6967
6968 ImplicitExceptionSpecification exceptSpec =
6969 ComputeDefaultedDtorExceptionSpec(classDecl);
6970
6971 // Replace the destructor's type.
6972 FunctionProtoType::ExtProtoInfo epi;
6973 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6974 epi.NumExceptions = exceptSpec.size();
6975 epi.Exceptions = exceptSpec.data();
6976 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6977
6978 destructor->setType(ty);
6979
6980 // FIXME: If the destructor has a body that could throw, and the newly created
6981 // spec doesn't allow exceptions, we should emit a warning, because this
6982 // change in behavior can break conforming C++03 programs at runtime.
6983 // However, we don't have a body yet, so it needs to be done somewhere else.
6984}
6985
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006986/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00006987/// \c To.
6988///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006989/// This routine is used to copy/move the members of a class with an
6990/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00006991/// copied are arrays, this routine builds for loops to copy them.
6992///
6993/// \param S The Sema object used for type-checking.
6994///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006995/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006996///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006997/// \param T The type of the expressions being copied/moved. Both expressions
6998/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006999///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007000/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007001///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007002/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007003///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007004/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007005/// Otherwise, it's a non-static member subobject.
7006///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007007/// \param Copying Whether we're copying or moving.
7008///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007009/// \param Depth Internal parameter recording the depth of the recursion.
7010///
7011/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007012static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007013BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007014 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007015 bool CopyingBaseSubobject, bool Copying,
7016 unsigned Depth = 0) {
7017 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007018 // Each subobject is assigned in the manner appropriate to its type:
7019 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007020 // - if the subobject is of class type, as if by a call to operator= with
7021 // the subobject as the object expression and the corresponding
7022 // subobject of x as a single function argument (as if by explicit
7023 // qualification; that is, ignoring any possible virtual overriding
7024 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007025 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7026 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7027
7028 // Look for operator=.
7029 DeclarationName Name
7030 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7031 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7032 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7033
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007034 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007035 LookupResult::Filter F = OpLookup.makeFilter();
7036 while (F.hasNext()) {
7037 NamedDecl *D = F.next();
7038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007039 if (Copying ? Method->isCopyAssignmentOperator() :
7040 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007041 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007042
Douglas Gregor06a9f362010-05-01 20:49:11 +00007043 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007044 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007045 F.done();
7046
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007047 // Suppress the protected check (C++ [class.protected]) for each of the
7048 // assignment operators we found. This strange dance is required when
7049 // we're assigning via a base classes's copy-assignment operator. To
7050 // ensure that we're getting the right base class subobject (without
7051 // ambiguities), we need to cast "this" to that subobject type; to
7052 // ensure that we don't go through the virtual call mechanism, we need
7053 // to qualify the operator= name with the base class (see below). However,
7054 // this means that if the base class has a protected copy assignment
7055 // operator, the protected member access check will fail. So, we
7056 // rewrite "protected" access to "public" access in this case, since we
7057 // know by construction that we're calling from a derived class.
7058 if (CopyingBaseSubobject) {
7059 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7060 L != LEnd; ++L) {
7061 if (L.getAccess() == AS_protected)
7062 L.setAccess(AS_public);
7063 }
7064 }
7065
Douglas Gregor06a9f362010-05-01 20:49:11 +00007066 // Create the nested-name-specifier that will be used to qualify the
7067 // reference to operator=; this is required to suppress the virtual
7068 // call mechanism.
7069 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007070 SS.MakeTrivial(S.Context,
7071 NestedNameSpecifier::Create(S.Context, 0, false,
7072 T.getTypePtr()),
7073 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007074
7075 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007076 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007077 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007078 /*FirstQualifierInScope=*/0, OpLookup,
7079 /*TemplateArgs=*/0,
7080 /*SuppressQualifierCheck=*/true);
7081 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007082 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007083
7084 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007085
John McCall60d7b3a2010-08-24 06:29:42 +00007086 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007087 OpEqualRef.takeAs<Expr>(),
7088 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007089 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007090 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007091
7092 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007093 }
John McCallb0207482010-03-16 06:11:48 +00007094
Douglas Gregor06a9f362010-05-01 20:49:11 +00007095 // - if the subobject is of scalar type, the built-in assignment
7096 // operator is used.
7097 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7098 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007099 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007100 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007101 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007102
7103 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007104 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007105
7106 // - if the subobject is an array, each element is assigned, in the
7107 // manner appropriate to the element type;
7108
7109 // Construct a loop over the array bounds, e.g.,
7110 //
7111 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7112 //
7113 // that will copy each of the array elements.
7114 QualType SizeType = S.Context.getSizeType();
7115
7116 // Create the iteration variable.
7117 IdentifierInfo *IterationVarName = 0;
7118 {
7119 llvm::SmallString<8> Str;
7120 llvm::raw_svector_ostream OS(Str);
7121 OS << "__i" << Depth;
7122 IterationVarName = &S.Context.Idents.get(OS.str());
7123 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007124 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007125 IterationVarName, SizeType,
7126 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007127 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007128
7129 // Initialize the iteration variable to zero.
7130 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007131 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007132
7133 // Create a reference to the iteration variable; we'll use this several
7134 // times throughout.
7135 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007136 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007137 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7138
7139 // Create the DeclStmt that holds the iteration variable.
7140 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7141
7142 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007143 llvm::APInt Upper
7144 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007145 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007146 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007147 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7148 BO_NE, S.Context.BoolTy,
7149 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007150
7151 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007152 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007153 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7154 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007155
7156 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007157 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7158 IterationVarRef, Loc));
7159 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7160 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007161 if (!Copying) // Cast to rvalue
7162 From = CastForMoving(S, From);
7163
7164 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007165 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7166 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007167 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007168 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007169 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007170
7171 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007172 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007173 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007174 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007175 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007176}
7177
Sean Hunt30de05c2011-05-14 05:23:20 +00007178std::pair<Sema::ImplicitExceptionSpecification, bool>
7179Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7180 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007181 if (ClassDecl->isInvalidDecl())
7182 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7183
Douglas Gregord3c35902010-07-01 16:36:15 +00007184 // C++ [class.copy]p10:
7185 // If the class definition does not explicitly declare a copy
7186 // assignment operator, one is declared implicitly.
7187 // The implicitly-defined copy assignment operator for a class X
7188 // will have the form
7189 //
7190 // X& X::operator=(const X&)
7191 //
7192 // if
7193 bool HasConstCopyAssignment = true;
7194
7195 // -- each direct base class B of X has a copy assignment operator
7196 // whose parameter is of type const B&, const volatile B& or B,
7197 // and
7198 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7199 BaseEnd = ClassDecl->bases_end();
7200 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007201 // We'll handle this below
7202 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7203 continue;
7204
Douglas Gregord3c35902010-07-01 16:36:15 +00007205 assert(!Base->getType()->isDependentType() &&
7206 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007207 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7208 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7209 &HasConstCopyAssignment);
7210 }
7211
7212 // In C++0x, the above citation has "or virtual added"
7213 if (LangOpts.CPlusPlus0x) {
7214 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7215 BaseEnd = ClassDecl->vbases_end();
7216 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7217 assert(!Base->getType()->isDependentType() &&
7218 "Cannot generate implicit members for class with dependent bases.");
7219 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7220 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7221 &HasConstCopyAssignment);
7222 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007223 }
7224
7225 // -- for all the nonstatic data members of X that are of a class
7226 // type M (or array thereof), each such class type has a copy
7227 // assignment operator whose parameter is of type const M&,
7228 // const volatile M& or M.
7229 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7230 FieldEnd = ClassDecl->field_end();
7231 HasConstCopyAssignment && Field != FieldEnd;
7232 ++Field) {
7233 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007234 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7235 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7236 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007237 }
7238 }
7239
7240 // Otherwise, the implicitly declared copy assignment operator will
7241 // have the form
7242 //
7243 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007244
Douglas Gregorb87786f2010-07-01 17:48:08 +00007245 // C++ [except.spec]p14:
7246 // An implicitly declared special member function (Clause 12) shall have an
7247 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007248
7249 // It is unspecified whether or not an implicit copy assignment operator
7250 // attempts to deduplicate calls to assignment operators of virtual bases are
7251 // made. As such, this exception specification is effectively unspecified.
7252 // Based on a similar decision made for constness in C++0x, we're erring on
7253 // the side of assuming such calls to be made regardless of whether they
7254 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007255 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007256 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007257 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7258 BaseEnd = ClassDecl->bases_end();
7259 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007260 if (Base->isVirtual())
7261 continue;
7262
Douglas Gregora376d102010-07-02 21:50:04 +00007263 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007264 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007265 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7266 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007267 ExceptSpec.CalledDecl(CopyAssign);
7268 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007269
7270 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7271 BaseEnd = ClassDecl->vbases_end();
7272 Base != BaseEnd; ++Base) {
7273 CXXRecordDecl *BaseClassDecl
7274 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7275 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7276 ArgQuals, false, 0))
7277 ExceptSpec.CalledDecl(CopyAssign);
7278 }
7279
Douglas Gregorb87786f2010-07-01 17:48:08 +00007280 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7281 FieldEnd = ClassDecl->field_end();
7282 Field != FieldEnd;
7283 ++Field) {
7284 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007285 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7286 if (CXXMethodDecl *CopyAssign =
7287 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7288 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007289 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007290 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007291
Sean Hunt30de05c2011-05-14 05:23:20 +00007292 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7293}
7294
7295CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7296 // Note: The following rules are largely analoguous to the copy
7297 // constructor rules. Note that virtual bases are not taken into account
7298 // for determining the argument type of the operator. Note also that
7299 // operators taking an object instead of a reference are allowed.
7300
7301 ImplicitExceptionSpecification Spec(Context);
7302 bool Const;
7303 llvm::tie(Spec, Const) =
7304 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7305
7306 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7307 QualType RetType = Context.getLValueReferenceType(ArgType);
7308 if (Const)
7309 ArgType = ArgType.withConst();
7310 ArgType = Context.getLValueReferenceType(ArgType);
7311
Douglas Gregord3c35902010-07-01 16:36:15 +00007312 // An implicitly-declared copy assignment operator is an inline public
7313 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007314 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007315 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007316 SourceLocation ClassLoc = ClassDecl->getLocation();
7317 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007318 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007319 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007320 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007321 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007322 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007323 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007324 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007325 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007326 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007327 CopyAssignment->setImplicit();
7328 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007329
7330 // Add the parameter to the operator.
7331 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007332 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007333 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007334 SC_None,
7335 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00007336 CopyAssignment->setParams(&FromParam, 1);
7337
Douglas Gregora376d102010-07-02 21:50:04 +00007338 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007339 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007340
Douglas Gregor23c94db2010-07-02 17:43:08 +00007341 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007342 PushOnScopeChains(CopyAssignment, S, false);
7343 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007344
Sean Hunt1ccbc542011-06-22 01:05:13 +00007345 // C++0x [class.copy]p18:
7346 // ... If the class definition declares a move constructor or move
7347 // assignment operator, the implicitly declared copy assignment operator is
7348 // defined as deleted; ...
7349 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7350 ClassDecl->hasUserDeclaredMoveAssignment() ||
7351 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007352 CopyAssignment->setDeletedAsWritten();
7353
Douglas Gregord3c35902010-07-01 16:36:15 +00007354 AddOverriddenMethods(ClassDecl, CopyAssignment);
7355 return CopyAssignment;
7356}
7357
Douglas Gregor06a9f362010-05-01 20:49:11 +00007358void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7359 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007360 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007361 CopyAssignOperator->isOverloadedOperator() &&
7362 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007363 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007364 "DefineImplicitCopyAssignment called for wrong function");
7365
7366 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7367
7368 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7369 CopyAssignOperator->setInvalidDecl();
7370 return;
7371 }
7372
7373 CopyAssignOperator->setUsed();
7374
7375 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007376 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007377
7378 // C++0x [class.copy]p30:
7379 // The implicitly-defined or explicitly-defaulted copy assignment operator
7380 // for a non-union class X performs memberwise copy assignment of its
7381 // subobjects. The direct base classes of X are assigned first, in the
7382 // order of their declaration in the base-specifier-list, and then the
7383 // immediate non-static data members of X are assigned, in the order in
7384 // which they were declared in the class definition.
7385
7386 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007387 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007388
7389 // The parameter for the "other" object, which we are copying from.
7390 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7391 Qualifiers OtherQuals = Other->getType().getQualifiers();
7392 QualType OtherRefType = Other->getType();
7393 if (const LValueReferenceType *OtherRef
7394 = OtherRefType->getAs<LValueReferenceType>()) {
7395 OtherRefType = OtherRef->getPointeeType();
7396 OtherQuals = OtherRefType.getQualifiers();
7397 }
7398
7399 // Our location for everything implicitly-generated.
7400 SourceLocation Loc = CopyAssignOperator->getLocation();
7401
7402 // Construct a reference to the "other" object. We'll be using this
7403 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007404 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007405 assert(OtherRef && "Reference to parameter cannot fail!");
7406
7407 // Construct the "this" pointer. We'll be using this throughout the generated
7408 // ASTs.
7409 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7410 assert(This && "Reference to this cannot fail!");
7411
7412 // Assign base classes.
7413 bool Invalid = false;
7414 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7415 E = ClassDecl->bases_end(); Base != E; ++Base) {
7416 // Form the assignment:
7417 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7418 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007419 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007420 Invalid = true;
7421 continue;
7422 }
7423
John McCallf871d0c2010-08-07 06:22:56 +00007424 CXXCastPath BasePath;
7425 BasePath.push_back(Base);
7426
Douglas Gregor06a9f362010-05-01 20:49:11 +00007427 // Construct the "from" expression, which is an implicit cast to the
7428 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007429 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007430 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7431 CK_UncheckedDerivedToBase,
7432 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007433
7434 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007435 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007436
7437 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007438 To = ImpCastExprToType(To.take(),
7439 Context.getCVRQualifiedType(BaseType,
7440 CopyAssignOperator->getTypeQualifiers()),
7441 CK_UncheckedDerivedToBase,
7442 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007443
7444 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007445 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007446 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007447 /*CopyingBaseSubobject=*/true,
7448 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007449 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007450 Diag(CurrentLocation, diag::note_member_synthesized_at)
7451 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7452 CopyAssignOperator->setInvalidDecl();
7453 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007454 }
7455
7456 // Success! Record the copy.
7457 Statements.push_back(Copy.takeAs<Expr>());
7458 }
7459
7460 // \brief Reference to the __builtin_memcpy function.
7461 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007462 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007463 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007464
7465 // Assign non-static members.
7466 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7467 FieldEnd = ClassDecl->field_end();
7468 Field != FieldEnd; ++Field) {
7469 // Check for members of reference type; we can't copy those.
7470 if (Field->getType()->isReferenceType()) {
7471 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7472 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7473 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007474 Diag(CurrentLocation, diag::note_member_synthesized_at)
7475 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007476 Invalid = true;
7477 continue;
7478 }
7479
7480 // Check for members of const-qualified, non-class type.
7481 QualType BaseType = Context.getBaseElementType(Field->getType());
7482 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7483 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7484 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7485 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007486 Diag(CurrentLocation, diag::note_member_synthesized_at)
7487 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007488 Invalid = true;
7489 continue;
7490 }
John McCallb77115d2011-06-17 00:18:42 +00007491
7492 // Suppress assigning zero-width bitfields.
7493 if (const Expr *Width = Field->getBitWidth())
7494 if (Width->EvaluateAsInt(Context) == 0)
7495 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007496
7497 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007498 if (FieldType->isIncompleteArrayType()) {
7499 assert(ClassDecl->hasFlexibleArrayMember() &&
7500 "Incomplete array type is not valid");
7501 continue;
7502 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007503
7504 // Build references to the field in the object we're copying from and to.
7505 CXXScopeSpec SS; // Intentionally empty
7506 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7507 LookupMemberName);
7508 MemberLookup.addDecl(*Field);
7509 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007510 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007511 Loc, /*IsArrow=*/false,
7512 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007513 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007514 Loc, /*IsArrow=*/true,
7515 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007516 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7517 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7518
7519 // If the field should be copied with __builtin_memcpy rather than via
7520 // explicit assignments, do so. This optimization only applies for arrays
7521 // of scalars and arrays of class type with trivial copy-assignment
7522 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007523 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007524 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007525 // Compute the size of the memory buffer to be copied.
7526 QualType SizeType = Context.getSizeType();
7527 llvm::APInt Size(Context.getTypeSize(SizeType),
7528 Context.getTypeSizeInChars(BaseType).getQuantity());
7529 for (const ConstantArrayType *Array
7530 = Context.getAsConstantArrayType(FieldType);
7531 Array;
7532 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007533 llvm::APInt ArraySize
7534 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007535 Size *= ArraySize;
7536 }
7537
7538 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007539 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7540 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007541
7542 bool NeedsCollectableMemCpy =
7543 (BaseType->isRecordType() &&
7544 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7545
7546 if (NeedsCollectableMemCpy) {
7547 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007548 // Create a reference to the __builtin_objc_memmove_collectable function.
7549 LookupResult R(*this,
7550 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007551 Loc, LookupOrdinaryName);
7552 LookupName(R, TUScope, true);
7553
7554 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7555 if (!CollectableMemCpy) {
7556 // Something went horribly wrong earlier, and we will have
7557 // complained about it.
7558 Invalid = true;
7559 continue;
7560 }
7561
7562 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7563 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007564 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007565 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7566 }
7567 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007568 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007569 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007570 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7571 LookupOrdinaryName);
7572 LookupName(R, TUScope, true);
7573
7574 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7575 if (!BuiltinMemCpy) {
7576 // Something went horribly wrong earlier, and we will have complained
7577 // about it.
7578 Invalid = true;
7579 continue;
7580 }
7581
7582 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7583 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007584 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007585 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7586 }
7587
John McCallca0408f2010-08-23 06:44:23 +00007588 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007589 CallArgs.push_back(To.takeAs<Expr>());
7590 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007591 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007592 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007593 if (NeedsCollectableMemCpy)
7594 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007595 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007596 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007597 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007598 else
7599 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007600 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007601 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007602 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007603
Douglas Gregor06a9f362010-05-01 20:49:11 +00007604 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7605 Statements.push_back(Call.takeAs<Expr>());
7606 continue;
7607 }
7608
7609 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007610 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007611 To.get(), From.get(),
7612 /*CopyingBaseSubobject=*/false,
7613 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007614 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007615 Diag(CurrentLocation, diag::note_member_synthesized_at)
7616 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7617 CopyAssignOperator->setInvalidDecl();
7618 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007619 }
7620
7621 // Success! Record the copy.
7622 Statements.push_back(Copy.takeAs<Stmt>());
7623 }
7624
7625 if (!Invalid) {
7626 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007627 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007628
John McCall60d7b3a2010-08-24 06:29:42 +00007629 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007630 if (Return.isInvalid())
7631 Invalid = true;
7632 else {
7633 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007634
7635 if (Trap.hasErrorOccurred()) {
7636 Diag(CurrentLocation, diag::note_member_synthesized_at)
7637 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7638 Invalid = true;
7639 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007640 }
7641 }
7642
7643 if (Invalid) {
7644 CopyAssignOperator->setInvalidDecl();
7645 return;
7646 }
7647
John McCall60d7b3a2010-08-24 06:29:42 +00007648 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007649 /*isStmtExpr=*/false);
7650 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7651 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007652
7653 if (ASTMutationListener *L = getASTMutationListener()) {
7654 L->CompletedImplicitDefinition(CopyAssignOperator);
7655 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007656}
7657
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007658Sema::ImplicitExceptionSpecification
7659Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7660 ImplicitExceptionSpecification ExceptSpec(Context);
7661
7662 if (ClassDecl->isInvalidDecl())
7663 return ExceptSpec;
7664
7665 // C++0x [except.spec]p14:
7666 // An implicitly declared special member function (Clause 12) shall have an
7667 // exception-specification. [...]
7668
7669 // It is unspecified whether or not an implicit move assignment operator
7670 // attempts to deduplicate calls to assignment operators of virtual bases are
7671 // made. As such, this exception specification is effectively unspecified.
7672 // Based on a similar decision made for constness in C++0x, we're erring on
7673 // the side of assuming such calls to be made regardless of whether they
7674 // actually happen.
7675 // Note that a move constructor is not implicitly declared when there are
7676 // virtual bases, but it can still be user-declared and explicitly defaulted.
7677 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7678 BaseEnd = ClassDecl->bases_end();
7679 Base != BaseEnd; ++Base) {
7680 if (Base->isVirtual())
7681 continue;
7682
7683 CXXRecordDecl *BaseClassDecl
7684 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7685 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7686 false, 0))
7687 ExceptSpec.CalledDecl(MoveAssign);
7688 }
7689
7690 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7691 BaseEnd = ClassDecl->vbases_end();
7692 Base != BaseEnd; ++Base) {
7693 CXXRecordDecl *BaseClassDecl
7694 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7695 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7696 false, 0))
7697 ExceptSpec.CalledDecl(MoveAssign);
7698 }
7699
7700 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7701 FieldEnd = ClassDecl->field_end();
7702 Field != FieldEnd;
7703 ++Field) {
7704 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7705 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7706 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7707 false, 0))
7708 ExceptSpec.CalledDecl(MoveAssign);
7709 }
7710 }
7711
7712 return ExceptSpec;
7713}
7714
7715CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7716 // Note: The following rules are largely analoguous to the move
7717 // constructor rules.
7718
7719 ImplicitExceptionSpecification Spec(
7720 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7721
7722 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7723 QualType RetType = Context.getLValueReferenceType(ArgType);
7724 ArgType = Context.getRValueReferenceType(ArgType);
7725
7726 // An implicitly-declared move assignment operator is an inline public
7727 // member of its class.
7728 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7729 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7730 SourceLocation ClassLoc = ClassDecl->getLocation();
7731 DeclarationNameInfo NameInfo(Name, ClassLoc);
7732 CXXMethodDecl *MoveAssignment
7733 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7734 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7735 /*TInfo=*/0, /*isStatic=*/false,
7736 /*StorageClassAsWritten=*/SC_None,
7737 /*isInline=*/true,
7738 /*isConstexpr=*/false,
7739 SourceLocation());
7740 MoveAssignment->setAccess(AS_public);
7741 MoveAssignment->setDefaulted();
7742 MoveAssignment->setImplicit();
7743 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7744
7745 // Add the parameter to the operator.
7746 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7747 ClassLoc, ClassLoc, /*Id=*/0,
7748 ArgType, /*TInfo=*/0,
7749 SC_None,
7750 SC_None, 0);
7751 MoveAssignment->setParams(&FromParam, 1);
7752
7753 // Note that we have added this copy-assignment operator.
7754 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7755
7756 // C++0x [class.copy]p9:
7757 // If the definition of a class X does not explicitly declare a move
7758 // assignment operator, one will be implicitly declared as defaulted if and
7759 // only if:
7760 // [...]
7761 // - the move assignment operator would not be implicitly defined as
7762 // deleted.
7763 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7764 // Cache this result so that we don't try to generate this over and over
7765 // on every lookup, leaking memory and wasting time.
7766 ClassDecl->setFailedImplicitMoveAssignment();
7767 return 0;
7768 }
7769
7770 if (Scope *S = getScopeForContext(ClassDecl))
7771 PushOnScopeChains(MoveAssignment, S, false);
7772 ClassDecl->addDecl(MoveAssignment);
7773
7774 AddOverriddenMethods(ClassDecl, MoveAssignment);
7775 return MoveAssignment;
7776}
7777
7778void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7779 CXXMethodDecl *MoveAssignOperator) {
7780 assert((MoveAssignOperator->isDefaulted() &&
7781 MoveAssignOperator->isOverloadedOperator() &&
7782 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7783 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7784 "DefineImplicitMoveAssignment called for wrong function");
7785
7786 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7787
7788 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7789 MoveAssignOperator->setInvalidDecl();
7790 return;
7791 }
7792
7793 MoveAssignOperator->setUsed();
7794
7795 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7796 DiagnosticErrorTrap Trap(Diags);
7797
7798 // C++0x [class.copy]p28:
7799 // The implicitly-defined or move assignment operator for a non-union class
7800 // X performs memberwise move assignment of its subobjects. The direct base
7801 // classes of X are assigned first, in the order of their declaration in the
7802 // base-specifier-list, and then the immediate non-static data members of X
7803 // are assigned, in the order in which they were declared in the class
7804 // definition.
7805
7806 // The statements that form the synthesized function body.
7807 ASTOwningVector<Stmt*> Statements(*this);
7808
7809 // The parameter for the "other" object, which we are move from.
7810 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7811 QualType OtherRefType = Other->getType()->
7812 getAs<RValueReferenceType>()->getPointeeType();
7813 assert(OtherRefType.getQualifiers() == 0 &&
7814 "Bad argument type of defaulted move assignment");
7815
7816 // Our location for everything implicitly-generated.
7817 SourceLocation Loc = MoveAssignOperator->getLocation();
7818
7819 // Construct a reference to the "other" object. We'll be using this
7820 // throughout the generated ASTs.
7821 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7822 assert(OtherRef && "Reference to parameter cannot fail!");
7823 // Cast to rvalue.
7824 OtherRef = CastForMoving(*this, OtherRef);
7825
7826 // Construct the "this" pointer. We'll be using this throughout the generated
7827 // ASTs.
7828 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7829 assert(This && "Reference to this cannot fail!");
7830
7831 // Assign base classes.
7832 bool Invalid = false;
7833 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7834 E = ClassDecl->bases_end(); Base != E; ++Base) {
7835 // Form the assignment:
7836 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7837 QualType BaseType = Base->getType().getUnqualifiedType();
7838 if (!BaseType->isRecordType()) {
7839 Invalid = true;
7840 continue;
7841 }
7842
7843 CXXCastPath BasePath;
7844 BasePath.push_back(Base);
7845
7846 // Construct the "from" expression, which is an implicit cast to the
7847 // appropriately-qualified base type.
7848 Expr *From = OtherRef;
7849 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00007850 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007851
7852 // Dereference "this".
7853 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7854
7855 // Implicitly cast "this" to the appropriately-qualified base type.
7856 To = ImpCastExprToType(To.take(),
7857 Context.getCVRQualifiedType(BaseType,
7858 MoveAssignOperator->getTypeQualifiers()),
7859 CK_UncheckedDerivedToBase,
7860 VK_LValue, &BasePath);
7861
7862 // Build the move.
7863 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7864 To.get(), From,
7865 /*CopyingBaseSubobject=*/true,
7866 /*Copying=*/false);
7867 if (Move.isInvalid()) {
7868 Diag(CurrentLocation, diag::note_member_synthesized_at)
7869 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7870 MoveAssignOperator->setInvalidDecl();
7871 return;
7872 }
7873
7874 // Success! Record the move.
7875 Statements.push_back(Move.takeAs<Expr>());
7876 }
7877
7878 // \brief Reference to the __builtin_memcpy function.
7879 Expr *BuiltinMemCpyRef = 0;
7880 // \brief Reference to the __builtin_objc_memmove_collectable function.
7881 Expr *CollectableMemCpyRef = 0;
7882
7883 // Assign non-static members.
7884 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7885 FieldEnd = ClassDecl->field_end();
7886 Field != FieldEnd; ++Field) {
7887 // Check for members of reference type; we can't move those.
7888 if (Field->getType()->isReferenceType()) {
7889 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7890 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7891 Diag(Field->getLocation(), diag::note_declared_at);
7892 Diag(CurrentLocation, diag::note_member_synthesized_at)
7893 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7894 Invalid = true;
7895 continue;
7896 }
7897
7898 // Check for members of const-qualified, non-class type.
7899 QualType BaseType = Context.getBaseElementType(Field->getType());
7900 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7901 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7902 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7903 Diag(Field->getLocation(), diag::note_declared_at);
7904 Diag(CurrentLocation, diag::note_member_synthesized_at)
7905 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7906 Invalid = true;
7907 continue;
7908 }
7909
7910 // Suppress assigning zero-width bitfields.
7911 if (const Expr *Width = Field->getBitWidth())
7912 if (Width->EvaluateAsInt(Context) == 0)
7913 continue;
7914
7915 QualType FieldType = Field->getType().getNonReferenceType();
7916 if (FieldType->isIncompleteArrayType()) {
7917 assert(ClassDecl->hasFlexibleArrayMember() &&
7918 "Incomplete array type is not valid");
7919 continue;
7920 }
7921
7922 // Build references to the field in the object we're copying from and to.
7923 CXXScopeSpec SS; // Intentionally empty
7924 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7925 LookupMemberName);
7926 MemberLookup.addDecl(*Field);
7927 MemberLookup.resolveKind();
7928 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7929 Loc, /*IsArrow=*/false,
7930 SS, 0, MemberLookup, 0);
7931 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7932 Loc, /*IsArrow=*/true,
7933 SS, 0, MemberLookup, 0);
7934 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7935 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7936
7937 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7938 "Member reference with rvalue base must be rvalue except for reference "
7939 "members, which aren't allowed for move assignment.");
7940
7941 // If the field should be copied with __builtin_memcpy rather than via
7942 // explicit assignments, do so. This optimization only applies for arrays
7943 // of scalars and arrays of class type with trivial move-assignment
7944 // operators.
7945 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7946 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7947 // Compute the size of the memory buffer to be copied.
7948 QualType SizeType = Context.getSizeType();
7949 llvm::APInt Size(Context.getTypeSize(SizeType),
7950 Context.getTypeSizeInChars(BaseType).getQuantity());
7951 for (const ConstantArrayType *Array
7952 = Context.getAsConstantArrayType(FieldType);
7953 Array;
7954 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7955 llvm::APInt ArraySize
7956 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7957 Size *= ArraySize;
7958 }
7959
Douglas Gregor45d3d712011-09-01 02:09:07 +00007960 // Take the address of the field references for "from" and "to". We
7961 // directly construct UnaryOperators here because semantic analysis
7962 // does not permit us to take the address of an xvalue.
7963 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7964 Context.getPointerType(From.get()->getType()),
7965 VK_RValue, OK_Ordinary, Loc);
7966 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7967 Context.getPointerType(To.get()->getType()),
7968 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007969
7970 bool NeedsCollectableMemCpy =
7971 (BaseType->isRecordType() &&
7972 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7973
7974 if (NeedsCollectableMemCpy) {
7975 if (!CollectableMemCpyRef) {
7976 // Create a reference to the __builtin_objc_memmove_collectable function.
7977 LookupResult R(*this,
7978 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7979 Loc, LookupOrdinaryName);
7980 LookupName(R, TUScope, true);
7981
7982 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7983 if (!CollectableMemCpy) {
7984 // Something went horribly wrong earlier, and we will have
7985 // complained about it.
7986 Invalid = true;
7987 continue;
7988 }
7989
7990 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7991 CollectableMemCpy->getType(),
7992 VK_LValue, Loc, 0).take();
7993 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7994 }
7995 }
7996 // Create a reference to the __builtin_memcpy builtin function.
7997 else if (!BuiltinMemCpyRef) {
7998 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7999 LookupOrdinaryName);
8000 LookupName(R, TUScope, true);
8001
8002 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8003 if (!BuiltinMemCpy) {
8004 // Something went horribly wrong earlier, and we will have complained
8005 // about it.
8006 Invalid = true;
8007 continue;
8008 }
8009
8010 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8011 BuiltinMemCpy->getType(),
8012 VK_LValue, Loc, 0).take();
8013 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8014 }
8015
8016 ASTOwningVector<Expr*> CallArgs(*this);
8017 CallArgs.push_back(To.takeAs<Expr>());
8018 CallArgs.push_back(From.takeAs<Expr>());
8019 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8020 ExprResult Call = ExprError();
8021 if (NeedsCollectableMemCpy)
8022 Call = ActOnCallExpr(/*Scope=*/0,
8023 CollectableMemCpyRef,
8024 Loc, move_arg(CallArgs),
8025 Loc);
8026 else
8027 Call = ActOnCallExpr(/*Scope=*/0,
8028 BuiltinMemCpyRef,
8029 Loc, move_arg(CallArgs),
8030 Loc);
8031
8032 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8033 Statements.push_back(Call.takeAs<Expr>());
8034 continue;
8035 }
8036
8037 // Build the move of this field.
8038 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8039 To.get(), From.get(),
8040 /*CopyingBaseSubobject=*/false,
8041 /*Copying=*/false);
8042 if (Move.isInvalid()) {
8043 Diag(CurrentLocation, diag::note_member_synthesized_at)
8044 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8045 MoveAssignOperator->setInvalidDecl();
8046 return;
8047 }
8048
8049 // Success! Record the copy.
8050 Statements.push_back(Move.takeAs<Stmt>());
8051 }
8052
8053 if (!Invalid) {
8054 // Add a "return *this;"
8055 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8056
8057 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8058 if (Return.isInvalid())
8059 Invalid = true;
8060 else {
8061 Statements.push_back(Return.takeAs<Stmt>());
8062
8063 if (Trap.hasErrorOccurred()) {
8064 Diag(CurrentLocation, diag::note_member_synthesized_at)
8065 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8066 Invalid = true;
8067 }
8068 }
8069 }
8070
8071 if (Invalid) {
8072 MoveAssignOperator->setInvalidDecl();
8073 return;
8074 }
8075
8076 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8077 /*isStmtExpr=*/false);
8078 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8079 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8080
8081 if (ASTMutationListener *L = getASTMutationListener()) {
8082 L->CompletedImplicitDefinition(MoveAssignOperator);
8083 }
8084}
8085
Sean Hunt49634cf2011-05-13 06:10:58 +00008086std::pair<Sema::ImplicitExceptionSpecification, bool>
8087Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008088 if (ClassDecl->isInvalidDecl())
8089 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8090
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008091 // C++ [class.copy]p5:
8092 // The implicitly-declared copy constructor for a class X will
8093 // have the form
8094 //
8095 // X::X(const X&)
8096 //
8097 // if
Sean Huntc530d172011-06-10 04:44:37 +00008098 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008099 bool HasConstCopyConstructor = true;
8100
8101 // -- each direct or virtual base class B of X has a copy
8102 // constructor whose first parameter is of type const B& or
8103 // const volatile B&, and
8104 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8105 BaseEnd = ClassDecl->bases_end();
8106 HasConstCopyConstructor && Base != BaseEnd;
8107 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008108 // Virtual bases are handled below.
8109 if (Base->isVirtual())
8110 continue;
8111
Douglas Gregor22584312010-07-02 23:41:54 +00008112 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008113 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008114 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8115 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008116 }
8117
8118 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8119 BaseEnd = ClassDecl->vbases_end();
8120 HasConstCopyConstructor && Base != BaseEnd;
8121 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008122 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008123 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008124 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8125 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008126 }
8127
8128 // -- for all the nonstatic data members of X that are of a
8129 // class type M (or array thereof), each such class type
8130 // has a copy constructor whose first parameter is of type
8131 // const M& or const volatile M&.
8132 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8133 FieldEnd = ClassDecl->field_end();
8134 HasConstCopyConstructor && Field != FieldEnd;
8135 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008136 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008137 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008138 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8139 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008140 }
8141 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008142 // Otherwise, the implicitly declared copy constructor will have
8143 // the form
8144 //
8145 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008146
Douglas Gregor0d405db2010-07-01 20:59:04 +00008147 // C++ [except.spec]p14:
8148 // An implicitly declared special member function (Clause 12) shall have an
8149 // exception-specification. [...]
8150 ImplicitExceptionSpecification ExceptSpec(Context);
8151 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8152 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8153 BaseEnd = ClassDecl->bases_end();
8154 Base != BaseEnd;
8155 ++Base) {
8156 // Virtual bases are handled below.
8157 if (Base->isVirtual())
8158 continue;
8159
Douglas Gregor22584312010-07-02 23:41:54 +00008160 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008161 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008162 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008163 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008164 ExceptSpec.CalledDecl(CopyConstructor);
8165 }
8166 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8167 BaseEnd = ClassDecl->vbases_end();
8168 Base != BaseEnd;
8169 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008170 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008171 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008172 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008173 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008174 ExceptSpec.CalledDecl(CopyConstructor);
8175 }
8176 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8177 FieldEnd = ClassDecl->field_end();
8178 Field != FieldEnd;
8179 ++Field) {
8180 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008181 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8182 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008183 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008184 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008185 }
8186 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008187
Sean Hunt49634cf2011-05-13 06:10:58 +00008188 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8189}
8190
8191CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8192 CXXRecordDecl *ClassDecl) {
8193 // C++ [class.copy]p4:
8194 // If the class definition does not explicitly declare a copy
8195 // constructor, one is declared implicitly.
8196
8197 ImplicitExceptionSpecification Spec(Context);
8198 bool Const;
8199 llvm::tie(Spec, Const) =
8200 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8201
8202 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8203 QualType ArgType = ClassType;
8204 if (Const)
8205 ArgType = ArgType.withConst();
8206 ArgType = Context.getLValueReferenceType(ArgType);
8207
8208 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8209
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008210 DeclarationName Name
8211 = Context.DeclarationNames.getCXXConstructorName(
8212 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008213 SourceLocation ClassLoc = ClassDecl->getLocation();
8214 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008215
8216 // An implicitly-declared copy constructor is an inline public
8217 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008218 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008219 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008220 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00008221 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008222 /*TInfo=*/0,
8223 /*isExplicit=*/false,
8224 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008225 /*isImplicitlyDeclared=*/true,
8226 // FIXME: apply the rules for definitions here
8227 /*isConstexpr=*/false);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008228 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008229 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008230 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8231
Douglas Gregor22584312010-07-02 23:41:54 +00008232 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008233 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8234
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008235 // Add the parameter to the constructor.
8236 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008237 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008238 /*IdentifierInfo=*/0,
8239 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008240 SC_None,
8241 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008242 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00008243
Douglas Gregor23c94db2010-07-02 17:43:08 +00008244 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008245 PushOnScopeChains(CopyConstructor, S, false);
8246 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008247
Sean Hunt1ccbc542011-06-22 01:05:13 +00008248 // C++0x [class.copy]p7:
8249 // ... If the class definition declares a move constructor or move
8250 // assignment operator, the implicitly declared constructor is defined as
8251 // deleted; ...
8252 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8253 ClassDecl->hasUserDeclaredMoveAssignment() ||
8254 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008255 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008256
8257 return CopyConstructor;
8258}
8259
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008260void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008261 CXXConstructorDecl *CopyConstructor) {
8262 assert((CopyConstructor->isDefaulted() &&
8263 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008264 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008265 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008266
Anders Carlsson63010a72010-04-23 16:24:12 +00008267 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008268 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008269
Douglas Gregor39957dc2010-05-01 15:04:51 +00008270 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008271 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008272
Sean Huntcbb67482011-01-08 20:30:50 +00008273 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008274 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008275 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008276 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008277 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008278 } else {
8279 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8280 CopyConstructor->getLocation(),
8281 MultiStmtArg(*this, 0, 0),
8282 /*isStmtExpr=*/false)
8283 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008284 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008285
8286 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008287
8288 if (ASTMutationListener *L = getASTMutationListener()) {
8289 L->CompletedImplicitDefinition(CopyConstructor);
8290 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008291}
8292
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008293Sema::ImplicitExceptionSpecification
8294Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8295 // C++ [except.spec]p14:
8296 // An implicitly declared special member function (Clause 12) shall have an
8297 // exception-specification. [...]
8298 ImplicitExceptionSpecification ExceptSpec(Context);
8299 if (ClassDecl->isInvalidDecl())
8300 return ExceptSpec;
8301
8302 // Direct base-class constructors.
8303 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8304 BEnd = ClassDecl->bases_end();
8305 B != BEnd; ++B) {
8306 if (B->isVirtual()) // Handled below.
8307 continue;
8308
8309 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8310 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8311 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8312 // If this is a deleted function, add it anyway. This might be conformant
8313 // with the standard. This might not. I'm not sure. It might not matter.
8314 if (Constructor)
8315 ExceptSpec.CalledDecl(Constructor);
8316 }
8317 }
8318
8319 // Virtual base-class constructors.
8320 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8321 BEnd = ClassDecl->vbases_end();
8322 B != BEnd; ++B) {
8323 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8324 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8325 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8326 // If this is a deleted function, add it anyway. This might be conformant
8327 // with the standard. This might not. I'm not sure. It might not matter.
8328 if (Constructor)
8329 ExceptSpec.CalledDecl(Constructor);
8330 }
8331 }
8332
8333 // Field constructors.
8334 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8335 FEnd = ClassDecl->field_end();
8336 F != FEnd; ++F) {
8337 if (F->hasInClassInitializer()) {
8338 if (Expr *E = F->getInClassInitializer())
8339 ExceptSpec.CalledExpr(E);
8340 else if (!F->isInvalidDecl())
8341 ExceptSpec.SetDelayed();
8342 } else if (const RecordType *RecordTy
8343 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8344 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8345 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8346 // If this is a deleted function, add it anyway. This might be conformant
8347 // with the standard. This might not. I'm not sure. It might not matter.
8348 // In particular, the problem is that this function never gets called. It
8349 // might just be ill-formed because this function attempts to refer to
8350 // a deleted function here.
8351 if (Constructor)
8352 ExceptSpec.CalledDecl(Constructor);
8353 }
8354 }
8355
8356 return ExceptSpec;
8357}
8358
8359CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8360 CXXRecordDecl *ClassDecl) {
8361 ImplicitExceptionSpecification Spec(
8362 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8363
8364 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8365 QualType ArgType = Context.getRValueReferenceType(ClassType);
8366
8367 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8368
8369 DeclarationName Name
8370 = Context.DeclarationNames.getCXXConstructorName(
8371 Context.getCanonicalType(ClassType));
8372 SourceLocation ClassLoc = ClassDecl->getLocation();
8373 DeclarationNameInfo NameInfo(Name, ClassLoc);
8374
8375 // C++0x [class.copy]p11:
8376 // An implicitly-declared copy/move constructor is an inline public
8377 // member of its class.
8378 CXXConstructorDecl *MoveConstructor
8379 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8380 Context.getFunctionType(Context.VoidTy,
8381 &ArgType, 1, EPI),
8382 /*TInfo=*/0,
8383 /*isExplicit=*/false,
8384 /*isInline=*/true,
8385 /*isImplicitlyDeclared=*/true,
8386 // FIXME: apply the rules for definitions here
8387 /*isConstexpr=*/false);
8388 MoveConstructor->setAccess(AS_public);
8389 MoveConstructor->setDefaulted();
8390 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8391
8392 // Add the parameter to the constructor.
8393 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8394 ClassLoc, ClassLoc,
8395 /*IdentifierInfo=*/0,
8396 ArgType, /*TInfo=*/0,
8397 SC_None,
8398 SC_None, 0);
8399 MoveConstructor->setParams(&FromParam, 1);
8400
8401 // C++0x [class.copy]p9:
8402 // If the definition of a class X does not explicitly declare a move
8403 // constructor, one will be implicitly declared as defaulted if and only if:
8404 // [...]
8405 // - the move constructor would not be implicitly defined as deleted.
8406 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8407 // Cache this result so that we don't try to generate this over and over
8408 // on every lookup, leaking memory and wasting time.
8409 ClassDecl->setFailedImplicitMoveConstructor();
8410 return 0;
8411 }
8412
8413 // Note that we have declared this constructor.
8414 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8415
8416 if (Scope *S = getScopeForContext(ClassDecl))
8417 PushOnScopeChains(MoveConstructor, S, false);
8418 ClassDecl->addDecl(MoveConstructor);
8419
8420 return MoveConstructor;
8421}
8422
8423void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8424 CXXConstructorDecl *MoveConstructor) {
8425 assert((MoveConstructor->isDefaulted() &&
8426 MoveConstructor->isMoveConstructor() &&
8427 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8428 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8429
8430 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8431 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8432
8433 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8434 DiagnosticErrorTrap Trap(Diags);
8435
8436 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8437 Trap.hasErrorOccurred()) {
8438 Diag(CurrentLocation, diag::note_member_synthesized_at)
8439 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8440 MoveConstructor->setInvalidDecl();
8441 } else {
8442 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8443 MoveConstructor->getLocation(),
8444 MultiStmtArg(*this, 0, 0),
8445 /*isStmtExpr=*/false)
8446 .takeAs<Stmt>());
8447 }
8448
8449 MoveConstructor->setUsed();
8450
8451 if (ASTMutationListener *L = getASTMutationListener()) {
8452 L->CompletedImplicitDefinition(MoveConstructor);
8453 }
8454}
8455
John McCall60d7b3a2010-08-24 06:29:42 +00008456ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008457Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008458 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008459 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008460 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008461 unsigned ConstructKind,
8462 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008463 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008464
Douglas Gregor2f599792010-04-02 18:24:57 +00008465 // C++0x [class.copy]p34:
8466 // When certain criteria are met, an implementation is allowed to
8467 // omit the copy/move construction of a class object, even if the
8468 // copy/move constructor and/or destructor for the object have
8469 // side effects. [...]
8470 // - when a temporary class object that has not been bound to a
8471 // reference (12.2) would be copied/moved to a class object
8472 // with the same cv-unqualified type, the copy/move operation
8473 // can be omitted by constructing the temporary object
8474 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008475 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008476 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008477 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008478 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008479 }
Mike Stump1eb44332009-09-09 15:08:12 +00008480
8481 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008482 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008483 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008484}
8485
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008486/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8487/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008488ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008489Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8490 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008491 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008492 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008493 unsigned ConstructKind,
8494 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008495 unsigned NumExprs = ExprArgs.size();
8496 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008497
Nick Lewycky909a70d2011-03-25 01:44:32 +00008498 for (specific_attr_iterator<NonNullAttr>
8499 i = Constructor->specific_attr_begin<NonNullAttr>(),
8500 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8501 const NonNullAttr *NonNull = *i;
8502 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8503 }
8504
Douglas Gregor7edfb692009-11-23 12:27:39 +00008505 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008506 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00008507 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00008508 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008509 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8510 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008511}
8512
Mike Stump1eb44332009-09-09 15:08:12 +00008513bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008514 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00008515 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008516 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008517 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008518 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008519 move(Exprs), false, CXXConstructExpr::CK_Complete,
8520 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008521 if (TempResult.isInvalid())
8522 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008523
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008524 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008525 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008526 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008527 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008528 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008529
Anders Carlssonfe2de492009-08-25 05:18:00 +00008530 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008531}
8532
John McCall68c6c9a2010-02-02 09:10:11 +00008533void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008534 if (VD->isInvalidDecl()) return;
8535
John McCall68c6c9a2010-02-02 09:10:11 +00008536 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008537 if (ClassDecl->isInvalidDecl()) return;
8538 if (ClassDecl->hasTrivialDestructor()) return;
8539 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008540
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008541 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8542 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8543 CheckDestructorAccess(VD->getLocation(), Destructor,
8544 PDiag(diag::err_access_dtor_var)
8545 << VD->getDeclName()
8546 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008547
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008548 if (!VD->hasGlobalStorage()) return;
8549
8550 // Emit warning for non-trivial dtor in global scope (a real global,
8551 // class-static, function-static).
8552 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8553
8554 // TODO: this should be re-enabled for static locals by !CXAAtExit
8555 if (!VD->isStaticLocal())
8556 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008557}
8558
Mike Stump1eb44332009-09-09 15:08:12 +00008559/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008560/// ActOnDeclarator, when a C++ direct initializer is present.
8561/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008562void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008563 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008564 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008565 SourceLocation RParenLoc,
8566 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00008567 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008568
8569 // If there is no declaration, there was an error parsing it. Just ignore
8570 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008571 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008572 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008573
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008574 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8575 if (!VDecl) {
8576 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8577 RealDecl->setInvalidDecl();
8578 return;
8579 }
8580
Richard Smith34b41d92011-02-20 03:19:35 +00008581 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8582 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008583 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8584 if (Exprs.size() > 1) {
8585 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8586 diag::err_auto_var_init_multiple_expressions)
8587 << VDecl->getDeclName() << VDecl->getType()
8588 << VDecl->getSourceRange();
8589 RealDecl->setInvalidDecl();
8590 return;
8591 }
8592
8593 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008594 TypeSourceInfo *DeducedType = 0;
8595 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008596 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8597 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8598 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008599 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008600 RealDecl->setInvalidDecl();
8601 return;
8602 }
Richard Smitha085da82011-03-17 16:11:59 +00008603 VDecl->setTypeSourceInfo(DeducedType);
8604 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008605
John McCallf85e1932011-06-15 23:02:42 +00008606 // In ARC, infer lifetime.
8607 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8608 VDecl->setInvalidDecl();
8609
Richard Smith34b41d92011-02-20 03:19:35 +00008610 // If this is a redeclaration, check that the type we just deduced matches
8611 // the previously declared type.
8612 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8613 MergeVarDeclTypes(VDecl, Old);
8614 }
8615
Douglas Gregor83ddad32009-08-26 21:14:46 +00008616 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008617 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008618 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8619 //
8620 // Clients that want to distinguish between the two forms, can check for
8621 // direct initializer using VarDecl::hasCXXDirectInitializer().
8622 // A major benefit is that clients that don't particularly care about which
8623 // exactly form was it (like the CodeGen) can handle both cases without
8624 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008625
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008626 // C++ 8.5p11:
8627 // The form of initialization (using parentheses or '=') is generally
8628 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008629 // class type.
8630
Douglas Gregor4dffad62010-02-11 22:55:30 +00008631 if (!VDecl->getType()->isDependentType() &&
8632 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00008633 diag::err_typecheck_decl_incomplete_type)) {
8634 VDecl->setInvalidDecl();
8635 return;
8636 }
8637
Douglas Gregor90f93822009-12-22 22:17:25 +00008638 // The variable can not have an abstract class type.
8639 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8640 diag::err_abstract_type_in_decl,
8641 AbstractVariableType))
8642 VDecl->setInvalidDecl();
8643
Sebastian Redl31310a22010-02-01 20:16:42 +00008644 const VarDecl *Def;
8645 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00008646 Diag(VDecl->getLocation(), diag::err_redefinition)
8647 << VDecl->getDeclName();
8648 Diag(Def->getLocation(), diag::note_previous_definition);
8649 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008650 return;
8651 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00008652
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008653 // C++ [class.static.data]p4
8654 // If a static data member is of const integral or const
8655 // enumeration type, its declaration in the class definition can
8656 // specify a constant-initializer which shall be an integral
8657 // constant expression (5.19). In that case, the member can appear
8658 // in integral constant expressions. The member shall still be
8659 // defined in a namespace scope if it is used in the program and the
8660 // namespace scope definition shall not contain an initializer.
8661 //
8662 // We already performed a redefinition check above, but for static
8663 // data members we also need to check whether there was an in-class
8664 // declaration with an initializer.
8665 const VarDecl* PrevInit = 0;
8666 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8667 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8668 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8669 return;
8670 }
8671
Douglas Gregora31040f2010-12-16 01:31:22 +00008672 bool IsDependent = false;
8673 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8674 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8675 VDecl->setInvalidDecl();
8676 return;
8677 }
8678
8679 if (Exprs.get()[I]->isTypeDependent())
8680 IsDependent = true;
8681 }
8682
Douglas Gregor4dffad62010-02-11 22:55:30 +00008683 // If either the declaration has a dependent type or if any of the
8684 // expressions is type-dependent, we represent the initialization
8685 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00008686 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00008687 // Let clients know that initialization was done with a direct initializer.
8688 VDecl->setCXXDirectInitializer(true);
8689
8690 // Store the initialization expressions as a ParenListExpr.
8691 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00008692 VDecl->setInit(new (Context) ParenListExpr(
8693 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8694 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00008695 return;
8696 }
Douglas Gregor90f93822009-12-22 22:17:25 +00008697
8698 // Capture the variable that is being initialized and the style of
8699 // initialization.
8700 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8701
8702 // FIXME: Poor source location information.
8703 InitializationKind Kind
8704 = InitializationKind::CreateDirect(VDecl->getLocation(),
8705 LParenLoc, RParenLoc);
8706
8707 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00008708 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00008709 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00008710 if (Result.isInvalid()) {
8711 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008712 return;
8713 }
John McCallb4eb64d2010-10-08 02:01:28 +00008714
8715 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00008716
Douglas Gregor53c374f2010-12-07 00:41:46 +00008717 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00008718 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008719 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008720
John McCall2998d6b2011-01-19 11:48:09 +00008721 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008722}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008723
Douglas Gregor39da0b82009-09-09 23:08:42 +00008724/// \brief Given a constructor and the set of arguments provided for the
8725/// constructor, convert the arguments and add any required default arguments
8726/// to form a proper call to this constructor.
8727///
8728/// \returns true if an error occurred, false otherwise.
8729bool
8730Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8731 MultiExprArg ArgsPtr,
8732 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00008733 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008734 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8735 unsigned NumArgs = ArgsPtr.size();
8736 Expr **Args = (Expr **)ArgsPtr.get();
8737
8738 const FunctionProtoType *Proto
8739 = Constructor->getType()->getAs<FunctionProtoType>();
8740 assert(Proto && "Constructor without a prototype?");
8741 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008742
8743 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008744 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008745 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008746 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008747 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008748
8749 VariadicCallType CallType =
8750 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008751 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008752 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8753 Proto, 0, Args, NumArgs, AllArgs,
8754 CallType);
8755 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8756 ConvertedArgs.push_back(AllArgs[i]);
8757 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008758}
8759
Anders Carlsson20d45d22009-12-12 00:32:00 +00008760static inline bool
8761CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8762 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008763 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00008764 if (isa<NamespaceDecl>(DC)) {
8765 return SemaRef.Diag(FnDecl->getLocation(),
8766 diag::err_operator_new_delete_declared_in_namespace)
8767 << FnDecl->getDeclName();
8768 }
8769
8770 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00008771 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008772 return SemaRef.Diag(FnDecl->getLocation(),
8773 diag::err_operator_new_delete_declared_static)
8774 << FnDecl->getDeclName();
8775 }
8776
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00008777 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00008778}
8779
Anders Carlsson156c78e2009-12-13 17:53:43 +00008780static inline bool
8781CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8782 CanQualType ExpectedResultType,
8783 CanQualType ExpectedFirstParamType,
8784 unsigned DependentParamTypeDiag,
8785 unsigned InvalidParamTypeDiag) {
8786 QualType ResultType =
8787 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8788
8789 // Check that the result type is not dependent.
8790 if (ResultType->isDependentType())
8791 return SemaRef.Diag(FnDecl->getLocation(),
8792 diag::err_operator_new_delete_dependent_result_type)
8793 << FnDecl->getDeclName() << ExpectedResultType;
8794
8795 // Check that the result type is what we expect.
8796 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8797 return SemaRef.Diag(FnDecl->getLocation(),
8798 diag::err_operator_new_delete_invalid_result_type)
8799 << FnDecl->getDeclName() << ExpectedResultType;
8800
8801 // A function template must have at least 2 parameters.
8802 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8803 return SemaRef.Diag(FnDecl->getLocation(),
8804 diag::err_operator_new_delete_template_too_few_parameters)
8805 << FnDecl->getDeclName();
8806
8807 // The function decl must have at least 1 parameter.
8808 if (FnDecl->getNumParams() == 0)
8809 return SemaRef.Diag(FnDecl->getLocation(),
8810 diag::err_operator_new_delete_too_few_parameters)
8811 << FnDecl->getDeclName();
8812
8813 // Check the the first parameter type is not dependent.
8814 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8815 if (FirstParamType->isDependentType())
8816 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8817 << FnDecl->getDeclName() << ExpectedFirstParamType;
8818
8819 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00008820 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00008821 ExpectedFirstParamType)
8822 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8823 << FnDecl->getDeclName() << ExpectedFirstParamType;
8824
8825 return false;
8826}
8827
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008828static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00008829CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008830 // C++ [basic.stc.dynamic.allocation]p1:
8831 // A program is ill-formed if an allocation function is declared in a
8832 // namespace scope other than global scope or declared static in global
8833 // scope.
8834 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8835 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00008836
8837 CanQualType SizeTy =
8838 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8839
8840 // C++ [basic.stc.dynamic.allocation]p1:
8841 // The return type shall be void*. The first parameter shall have type
8842 // std::size_t.
8843 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8844 SizeTy,
8845 diag::err_operator_new_dependent_param_type,
8846 diag::err_operator_new_param_type))
8847 return true;
8848
8849 // C++ [basic.stc.dynamic.allocation]p1:
8850 // The first parameter shall not have an associated default argument.
8851 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00008852 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00008853 diag::err_operator_new_default_arg)
8854 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8855
8856 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00008857}
8858
8859static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008860CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8861 // C++ [basic.stc.dynamic.deallocation]p1:
8862 // A program is ill-formed if deallocation functions are declared in a
8863 // namespace scope other than global scope or declared static in global
8864 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00008865 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8866 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008867
8868 // C++ [basic.stc.dynamic.deallocation]p2:
8869 // Each deallocation function shall return void and its first parameter
8870 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00008871 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8872 SemaRef.Context.VoidPtrTy,
8873 diag::err_operator_delete_dependent_param_type,
8874 diag::err_operator_delete_param_type))
8875 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008876
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008877 return false;
8878}
8879
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008880/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8881/// of this overloaded operator is well-formed. If so, returns false;
8882/// otherwise, emits appropriate diagnostics and returns true.
8883bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008884 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008885 "Expected an overloaded operator declaration");
8886
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008887 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8888
Mike Stump1eb44332009-09-09 15:08:12 +00008889 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008890 // The allocation and deallocation functions, operator new,
8891 // operator new[], operator delete and operator delete[], are
8892 // described completely in 3.7.3. The attributes and restrictions
8893 // found in the rest of this subclause do not apply to them unless
8894 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00008895 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008896 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00008897
Anders Carlssona3ccda52009-12-12 00:26:23 +00008898 if (Op == OO_New || Op == OO_Array_New)
8899 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008900
8901 // C++ [over.oper]p6:
8902 // An operator function shall either be a non-static member
8903 // function or be a non-member function and have at least one
8904 // parameter whose type is a class, a reference to a class, an
8905 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008906 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8907 if (MethodDecl->isStatic())
8908 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008909 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008910 } else {
8911 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008912 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8913 ParamEnd = FnDecl->param_end();
8914 Param != ParamEnd; ++Param) {
8915 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00008916 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8917 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008918 ClassOrEnumParam = true;
8919 break;
8920 }
8921 }
8922
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008923 if (!ClassOrEnumParam)
8924 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008925 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008926 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008927 }
8928
8929 // C++ [over.oper]p8:
8930 // An operator function cannot have default arguments (8.3.6),
8931 // except where explicitly stated below.
8932 //
Mike Stump1eb44332009-09-09 15:08:12 +00008933 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008934 // (C++ [over.call]p1).
8935 if (Op != OO_Call) {
8936 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8937 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00008938 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00008939 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00008940 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00008941 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008942 }
8943 }
8944
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008945 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8946 { false, false, false }
8947#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8948 , { Unary, Binary, MemberOnly }
8949#include "clang/Basic/OperatorKinds.def"
8950 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008951
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008952 bool CanBeUnaryOperator = OperatorUses[Op][0];
8953 bool CanBeBinaryOperator = OperatorUses[Op][1];
8954 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008955
8956 // C++ [over.oper]p8:
8957 // [...] Operator functions cannot have more or fewer parameters
8958 // than the number required for the corresponding operator, as
8959 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00008960 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008961 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008962 if (Op != OO_Call &&
8963 ((NumParams == 1 && !CanBeUnaryOperator) ||
8964 (NumParams == 2 && !CanBeBinaryOperator) ||
8965 (NumParams < 1) || (NumParams > 2))) {
8966 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00008967 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008968 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008969 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008970 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008971 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008972 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00008973 assert(CanBeBinaryOperator &&
8974 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00008975 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008976 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008977
Chris Lattner416e46f2008-11-21 07:57:12 +00008978 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008979 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008980 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00008981
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008982 // Overloaded operators other than operator() cannot be variadic.
8983 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00008984 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008985 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008986 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008987 }
8988
8989 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008990 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
8991 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008992 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008993 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008994 }
8995
8996 // C++ [over.inc]p1:
8997 // The user-defined function called operator++ implements the
8998 // prefix and postfix ++ operator. If this function is a member
8999 // function with no parameters, or a non-member function with one
9000 // parameter of class or enumeration type, it defines the prefix
9001 // increment operator ++ for objects of that type. If the function
9002 // is a member function with one parameter (which shall be of type
9003 // int) or a non-member function with two parameters (the second
9004 // of which shall be of type int), it defines the postfix
9005 // increment operator ++ for objects of that type.
9006 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9007 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9008 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009009 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009010 ParamIsInt = BT->getKind() == BuiltinType::Int;
9011
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009012 if (!ParamIsInt)
9013 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009014 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009015 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009016 }
9017
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009018 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009019}
Chris Lattner5a003a42008-12-17 07:09:26 +00009020
Sean Hunta6c058d2010-01-13 09:01:02 +00009021/// CheckLiteralOperatorDeclaration - Check whether the declaration
9022/// of this literal operator function is well-formed. If so, returns
9023/// false; otherwise, emits appropriate diagnostics and returns true.
9024bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9025 DeclContext *DC = FnDecl->getDeclContext();
9026 Decl::Kind Kind = DC->getDeclKind();
9027 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9028 Kind != Decl::LinkageSpec) {
9029 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9030 << FnDecl->getDeclName();
9031 return true;
9032 }
9033
9034 bool Valid = false;
9035
Sean Hunt216c2782010-04-07 23:11:06 +00009036 // template <char...> type operator "" name() is the only valid template
9037 // signature, and the only valid signature with no parameters.
9038 if (FnDecl->param_size() == 0) {
9039 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9040 // Must have only one template parameter
9041 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9042 if (Params->size() == 1) {
9043 NonTypeTemplateParmDecl *PmDecl =
9044 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009045
Sean Hunt216c2782010-04-07 23:11:06 +00009046 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009047 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9048 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9049 Valid = true;
9050 }
9051 }
9052 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009053 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009054 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9055
Sean Hunta6c058d2010-01-13 09:01:02 +00009056 QualType T = (*Param)->getType();
9057
Sean Hunt30019c02010-04-07 22:57:35 +00009058 // unsigned long long int, long double, and any character type are allowed
9059 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009060 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9061 Context.hasSameType(T, Context.LongDoubleTy) ||
9062 Context.hasSameType(T, Context.CharTy) ||
9063 Context.hasSameType(T, Context.WCharTy) ||
9064 Context.hasSameType(T, Context.Char16Ty) ||
9065 Context.hasSameType(T, Context.Char32Ty)) {
9066 if (++Param == FnDecl->param_end())
9067 Valid = true;
9068 goto FinishedParams;
9069 }
9070
Sean Hunt30019c02010-04-07 22:57:35 +00009071 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009072 const PointerType *PT = T->getAs<PointerType>();
9073 if (!PT)
9074 goto FinishedParams;
9075 T = PT->getPointeeType();
9076 if (!T.isConstQualified())
9077 goto FinishedParams;
9078 T = T.getUnqualifiedType();
9079
9080 // Move on to the second parameter;
9081 ++Param;
9082
9083 // If there is no second parameter, the first must be a const char *
9084 if (Param == FnDecl->param_end()) {
9085 if (Context.hasSameType(T, Context.CharTy))
9086 Valid = true;
9087 goto FinishedParams;
9088 }
9089
9090 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9091 // are allowed as the first parameter to a two-parameter function
9092 if (!(Context.hasSameType(T, Context.CharTy) ||
9093 Context.hasSameType(T, Context.WCharTy) ||
9094 Context.hasSameType(T, Context.Char16Ty) ||
9095 Context.hasSameType(T, Context.Char32Ty)))
9096 goto FinishedParams;
9097
9098 // The second and final parameter must be an std::size_t
9099 T = (*Param)->getType().getUnqualifiedType();
9100 if (Context.hasSameType(T, Context.getSizeType()) &&
9101 ++Param == FnDecl->param_end())
9102 Valid = true;
9103 }
9104
9105 // FIXME: This diagnostic is absolutely terrible.
9106FinishedParams:
9107 if (!Valid) {
9108 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9109 << FnDecl->getDeclName();
9110 return true;
9111 }
9112
Douglas Gregor1155c422011-08-30 22:40:35 +00009113 StringRef LiteralName
9114 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9115 if (LiteralName[0] != '_') {
9116 // C++0x [usrlit.suffix]p1:
9117 // Literal suffix identifiers that do not start with an underscore are
9118 // reserved for future standardization.
9119 bool IsHexFloat = true;
9120 if (LiteralName.size() > 1 &&
9121 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9122 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9123 if (!isdigit(LiteralName[I])) {
9124 IsHexFloat = false;
9125 break;
9126 }
9127 }
9128 }
9129
9130 if (IsHexFloat)
9131 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9132 << LiteralName;
9133 else
9134 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9135 }
9136
Sean Hunta6c058d2010-01-13 09:01:02 +00009137 return false;
9138}
9139
Douglas Gregor074149e2009-01-05 19:45:36 +00009140/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9141/// linkage specification, including the language and (if present)
9142/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9143/// the location of the language string literal, which is provided
9144/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9145/// the '{' brace. Otherwise, this linkage specification does not
9146/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009147Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9148 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009149 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009150 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009151 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009152 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009153 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009154 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009155 Language = LinkageSpecDecl::lang_cxx;
9156 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009157 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009158 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009159 }
Mike Stump1eb44332009-09-09 15:08:12 +00009160
Chris Lattnercc98eac2008-12-17 07:13:27 +00009161 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009162
Douglas Gregor074149e2009-01-05 19:45:36 +00009163 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009164 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009165 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009166 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009167 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009168}
9169
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009170/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009171/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9172/// valid, it's the position of the closing '}' brace in a linkage
9173/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009174Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009175 Decl *LinkageSpec,
9176 SourceLocation RBraceLoc) {
9177 if (LinkageSpec) {
9178 if (RBraceLoc.isValid()) {
9179 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9180 LSDecl->setRBraceLoc(RBraceLoc);
9181 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009182 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009183 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009184 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009185}
9186
Douglas Gregord308e622009-05-18 20:51:54 +00009187/// \brief Perform semantic analysis for the variable declaration that
9188/// occurs within a C++ catch clause, returning the newly-created
9189/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009190VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009191 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009192 SourceLocation StartLoc,
9193 SourceLocation Loc,
9194 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009195 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009196 QualType ExDeclType = TInfo->getType();
9197
Sebastian Redl4b07b292008-12-22 19:15:10 +00009198 // Arrays and functions decay.
9199 if (ExDeclType->isArrayType())
9200 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9201 else if (ExDeclType->isFunctionType())
9202 ExDeclType = Context.getPointerType(ExDeclType);
9203
9204 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9205 // The exception-declaration shall not denote a pointer or reference to an
9206 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009207 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009208 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009209 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009210 Invalid = true;
9211 }
Douglas Gregord308e622009-05-18 20:51:54 +00009212
Douglas Gregora2762912010-03-08 01:47:36 +00009213 // GCC allows catching pointers and references to incomplete types
9214 // as an extension; so do we, but we warn by default.
9215
Sebastian Redl4b07b292008-12-22 19:15:10 +00009216 QualType BaseType = ExDeclType;
9217 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009218 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009219 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009220 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009221 BaseType = Ptr->getPointeeType();
9222 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009223 DK = diag::ext_catch_incomplete_ptr;
9224 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009225 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009226 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009227 BaseType = Ref->getPointeeType();
9228 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009229 DK = diag::ext_catch_incomplete_ref;
9230 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009231 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009232 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009233 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9234 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009235 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009236
Mike Stump1eb44332009-09-09 15:08:12 +00009237 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009238 RequireNonAbstractType(Loc, ExDeclType,
9239 diag::err_abstract_type_in_decl,
9240 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009241 Invalid = true;
9242
John McCall5a180392010-07-24 00:37:23 +00009243 // Only the non-fragile NeXT runtime currently supports C++ catches
9244 // of ObjC types, and no runtime supports catching ObjC types by value.
9245 if (!Invalid && getLangOptions().ObjC1) {
9246 QualType T = ExDeclType;
9247 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9248 T = RT->getPointeeType();
9249
9250 if (T->isObjCObjectType()) {
9251 Diag(Loc, diag::err_objc_object_catch);
9252 Invalid = true;
9253 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009254 if (!getLangOptions().ObjCNonFragileABI)
9255 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009256 }
9257 }
9258
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009259 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9260 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009261 ExDecl->setExceptionVariable(true);
9262
Douglas Gregorc41b8782011-07-06 18:14:43 +00009263 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009264 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009265 // C++ [except.handle]p16:
9266 // The object declared in an exception-declaration or, if the
9267 // exception-declaration does not specify a name, a temporary (12.2) is
9268 // copy-initialized (8.5) from the exception object. [...]
9269 // The object is destroyed when the handler exits, after the destruction
9270 // of any automatic objects initialized within the handler.
9271 //
9272 // We just pretend to initialize the object with itself, then make sure
9273 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009274 QualType initType = ExDeclType;
9275
9276 InitializedEntity entity =
9277 InitializedEntity::InitializeVariable(ExDecl);
9278 InitializationKind initKind =
9279 InitializationKind::CreateCopy(Loc, SourceLocation());
9280
9281 Expr *opaqueValue =
9282 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9283 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9284 ExprResult result = sequence.Perform(*this, entity, initKind,
9285 MultiExprArg(&opaqueValue, 1));
9286 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009287 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009288 else {
9289 // If the constructor used was non-trivial, set this as the
9290 // "initializer".
9291 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9292 if (!construct->getConstructor()->isTrivial()) {
9293 Expr *init = MaybeCreateExprWithCleanups(construct);
9294 ExDecl->setInit(init);
9295 }
9296
9297 // And make sure it's destructable.
9298 FinalizeVarWithDestructor(ExDecl, recordType);
9299 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009300 }
9301 }
9302
Douglas Gregord308e622009-05-18 20:51:54 +00009303 if (Invalid)
9304 ExDecl->setInvalidDecl();
9305
9306 return ExDecl;
9307}
9308
9309/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9310/// handler.
John McCalld226f652010-08-21 09:40:31 +00009311Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009312 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009313 bool Invalid = D.isInvalidType();
9314
9315 // Check for unexpanded parameter packs.
9316 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9317 UPPC_ExceptionType)) {
9318 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9319 D.getIdentifierLoc());
9320 Invalid = true;
9321 }
9322
Sebastian Redl4b07b292008-12-22 19:15:10 +00009323 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009324 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009325 LookupOrdinaryName,
9326 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009327 // The scope should be freshly made just for us. There is just no way
9328 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009329 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009330 if (PrevDecl->isTemplateParameter()) {
9331 // Maybe we will complain about the shadowed template parameter.
9332 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009333 }
9334 }
9335
Chris Lattnereaaebc72009-04-25 08:06:05 +00009336 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009337 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9338 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009339 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009340 }
9341
Douglas Gregor83cb9422010-09-09 17:09:21 +00009342 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009343 D.getSourceRange().getBegin(),
9344 D.getIdentifierLoc(),
9345 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009346 if (Invalid)
9347 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009348
Sebastian Redl4b07b292008-12-22 19:15:10 +00009349 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009350 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009351 PushOnScopeChains(ExDecl, S);
9352 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009353 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009354
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009355 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009356 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009357}
Anders Carlssonfb311762009-03-14 00:25:26 +00009358
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009359Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009360 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009361 Expr *AssertMessageExpr_,
9362 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009363 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009364
Anders Carlssonc3082412009-03-14 00:33:21 +00009365 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9366 llvm::APSInt Value(32);
9367 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009368 Diag(StaticAssertLoc,
9369 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00009370 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009371 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00009372 }
Anders Carlssonfb311762009-03-14 00:25:26 +00009373
Anders Carlssonc3082412009-03-14 00:33:21 +00009374 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009375 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009376 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009377 }
9378 }
Mike Stump1eb44332009-09-09 15:08:12 +00009379
Douglas Gregor399ad972010-12-15 23:55:21 +00009380 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9381 return 0;
9382
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009383 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9384 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009385
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009386 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009387 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009388}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009389
Douglas Gregor1d869352010-04-07 16:53:43 +00009390/// \brief Perform semantic analysis of the given friend type declaration.
9391///
9392/// \returns A friend declaration that.
9393FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9394 TypeSourceInfo *TSInfo) {
9395 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9396
9397 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009398 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009399
Douglas Gregor06245bf2010-04-07 17:57:12 +00009400 if (!getLangOptions().CPlusPlus0x) {
9401 // C++03 [class.friend]p2:
9402 // An elaborated-type-specifier shall be used in a friend declaration
9403 // for a class.*
9404 //
9405 // * The class-key of the elaborated-type-specifier is required.
9406 if (!ActiveTemplateInstantiations.empty()) {
9407 // Do not complain about the form of friend template types during
9408 // template instantiation; we will already have complained when the
9409 // template was declared.
9410 } else if (!T->isElaboratedTypeSpecifier()) {
9411 // If we evaluated the type to a record type, suggest putting
9412 // a tag in front.
9413 if (const RecordType *RT = T->getAs<RecordType>()) {
9414 RecordDecl *RD = RT->getDecl();
9415
9416 std::string InsertionText = std::string(" ") + RD->getKindName();
9417
9418 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9419 << (unsigned) RD->getTagKind()
9420 << T
9421 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9422 InsertionText);
9423 } else {
9424 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9425 << T
9426 << SourceRange(FriendLoc, TypeRange.getEnd());
9427 }
9428 } else if (T->getAs<EnumType>()) {
9429 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009430 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009431 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009432 }
9433 }
9434
Douglas Gregor06245bf2010-04-07 17:57:12 +00009435 // C++0x [class.friend]p3:
9436 // If the type specifier in a friend declaration designates a (possibly
9437 // cv-qualified) class type, that class is declared as a friend; otherwise,
9438 // the friend declaration is ignored.
9439
9440 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9441 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009442
9443 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9444}
9445
John McCall9a34edb2010-10-19 01:40:49 +00009446/// Handle a friend tag declaration where the scope specifier was
9447/// templated.
9448Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9449 unsigned TagSpec, SourceLocation TagLoc,
9450 CXXScopeSpec &SS,
9451 IdentifierInfo *Name, SourceLocation NameLoc,
9452 AttributeList *Attr,
9453 MultiTemplateParamsArg TempParamLists) {
9454 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9455
9456 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009457 bool Invalid = false;
9458
9459 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009460 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009461 TempParamLists.get(),
9462 TempParamLists.size(),
9463 /*friend*/ true,
9464 isExplicitSpecialization,
9465 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009466 if (TemplateParams->size() > 0) {
9467 // This is a declaration of a class template.
9468 if (Invalid)
9469 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009470
Eric Christopher4110e132011-07-21 05:34:24 +00009471 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9472 SS, Name, NameLoc, Attr,
9473 TemplateParams, AS_public,
Douglas Gregor8d267c52011-09-09 02:06:17 +00009474 /*IsModulePrivate=*/false,
Eric Christopher4110e132011-07-21 05:34:24 +00009475 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009476 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009477 } else {
9478 // The "template<>" header is extraneous.
9479 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9480 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9481 isExplicitSpecialization = true;
9482 }
9483 }
9484
9485 if (Invalid) return 0;
9486
9487 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9488
9489 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009490 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009491 if (TempParamLists.get()[I]->size()) {
9492 isAllExplicitSpecializations = false;
9493 break;
9494 }
9495 }
9496
9497 // FIXME: don't ignore attributes.
9498
9499 // If it's explicit specializations all the way down, just forget
9500 // about the template header and build an appropriate non-templated
9501 // friend. TODO: for source fidelity, remember the headers.
9502 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00009503 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009504 ElaboratedTypeKeyword Keyword
9505 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009506 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009507 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009508 if (T.isNull())
9509 return 0;
9510
9511 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9512 if (isa<DependentNameType>(T)) {
9513 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9514 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009515 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009516 TL.setNameLoc(NameLoc);
9517 } else {
9518 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9519 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009520 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009521 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9522 }
9523
9524 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9525 TSI, FriendLoc);
9526 Friend->setAccess(AS_public);
9527 CurContext->addDecl(Friend);
9528 return Friend;
9529 }
9530
9531 // Handle the case of a templated-scope friend class. e.g.
9532 // template <class T> class A<T>::B;
9533 // FIXME: we don't support these right now.
9534 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9535 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9536 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9537 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9538 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009539 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009540 TL.setNameLoc(NameLoc);
9541
9542 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9543 TSI, FriendLoc);
9544 Friend->setAccess(AS_public);
9545 Friend->setUnsupportedFriend(true);
9546 CurContext->addDecl(Friend);
9547 return Friend;
9548}
9549
9550
John McCalldd4a3b02009-09-16 22:47:08 +00009551/// Handle a friend type declaration. This works in tandem with
9552/// ActOnTag.
9553///
9554/// Notes on friend class templates:
9555///
9556/// We generally treat friend class declarations as if they were
9557/// declaring a class. So, for example, the elaborated type specifier
9558/// in a friend declaration is required to obey the restrictions of a
9559/// class-head (i.e. no typedefs in the scope chain), template
9560/// parameters are required to match up with simple template-ids, &c.
9561/// However, unlike when declaring a template specialization, it's
9562/// okay to refer to a template specialization without an empty
9563/// template parameter declaration, e.g.
9564/// friend class A<T>::B<unsigned>;
9565/// We permit this as a special case; if there are any template
9566/// parameters present at all, require proper matching, i.e.
9567/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009568Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009569 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009570 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009571
9572 assert(DS.isFriendSpecified());
9573 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9574
John McCalldd4a3b02009-09-16 22:47:08 +00009575 // Try to convert the decl specifier to a type. This works for
9576 // friend templates because ActOnTag never produces a ClassTemplateDecl
9577 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009578 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009579 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9580 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009581 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009582 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009583
Douglas Gregor6ccab972010-12-16 01:14:37 +00009584 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9585 return 0;
9586
John McCalldd4a3b02009-09-16 22:47:08 +00009587 // This is definitely an error in C++98. It's probably meant to
9588 // be forbidden in C++0x, too, but the specification is just
9589 // poorly written.
9590 //
9591 // The problem is with declarations like the following:
9592 // template <T> friend A<T>::foo;
9593 // where deciding whether a class C is a friend or not now hinges
9594 // on whether there exists an instantiation of A that causes
9595 // 'foo' to equal C. There are restrictions on class-heads
9596 // (which we declare (by fiat) elaborated friend declarations to
9597 // be) that makes this tractable.
9598 //
9599 // FIXME: handle "template <> friend class A<T>;", which
9600 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009601 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009602 Diag(Loc, diag::err_tagless_friend_type_template)
9603 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009604 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009605 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009606
John McCall02cace72009-08-28 07:59:38 +00009607 // C++98 [class.friend]p1: A friend of a class is a function
9608 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009609 // This is fixed in DR77, which just barely didn't make the C++03
9610 // deadline. It's also a very silly restriction that seriously
9611 // affects inner classes and which nobody else seems to implement;
9612 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009613 //
9614 // But note that we could warn about it: it's always useless to
9615 // friend one of your own members (it's not, however, worthless to
9616 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009617
John McCalldd4a3b02009-09-16 22:47:08 +00009618 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009619 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009620 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009621 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009622 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009623 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009624 DS.getFriendSpecLoc());
9625 else
Douglas Gregor1d869352010-04-07 16:53:43 +00009626 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9627
9628 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009629 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009630
John McCalldd4a3b02009-09-16 22:47:08 +00009631 D->setAccess(AS_public);
9632 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009633
John McCalld226f652010-08-21 09:40:31 +00009634 return D;
John McCall02cace72009-08-28 07:59:38 +00009635}
9636
John McCall337ec3d2010-10-12 23:13:28 +00009637Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9638 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009639 const DeclSpec &DS = D.getDeclSpec();
9640
9641 assert(DS.isFriendSpecified());
9642 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9643
9644 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009645 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9646 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00009647
9648 // C++ [class.friend]p1
9649 // A friend of a class is a function or class....
9650 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009651 // It *doesn't* see through dependent types, which is correct
9652 // according to [temp.arg.type]p3:
9653 // If a declaration acquires a function type through a
9654 // type dependent on a template-parameter and this causes
9655 // a declaration that does not use the syntactic form of a
9656 // function declarator to have a function type, the program
9657 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00009658 if (!T->isFunctionType()) {
9659 Diag(Loc, diag::err_unexpected_friend);
9660
9661 // It might be worthwhile to try to recover by creating an
9662 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009663 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009664 }
9665
9666 // C++ [namespace.memdef]p3
9667 // - If a friend declaration in a non-local class first declares a
9668 // class or function, the friend class or function is a member
9669 // of the innermost enclosing namespace.
9670 // - The name of the friend is not found by simple name lookup
9671 // until a matching declaration is provided in that namespace
9672 // scope (either before or after the class declaration granting
9673 // friendship).
9674 // - If a friend function is called, its name may be found by the
9675 // name lookup that considers functions from namespaces and
9676 // classes associated with the types of the function arguments.
9677 // - When looking for a prior declaration of a class or a function
9678 // declared as a friend, scopes outside the innermost enclosing
9679 // namespace scope are not considered.
9680
John McCall337ec3d2010-10-12 23:13:28 +00009681 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009682 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9683 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009684 assert(Name);
9685
Douglas Gregor6ccab972010-12-16 01:14:37 +00009686 // Check for unexpanded parameter packs.
9687 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9688 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9689 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9690 return 0;
9691
John McCall67d1a672009-08-06 02:15:43 +00009692 // The context we found the declaration in, or in which we should
9693 // create the declaration.
9694 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009695 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009696 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009697 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009698
John McCall337ec3d2010-10-12 23:13:28 +00009699 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009700
John McCall337ec3d2010-10-12 23:13:28 +00009701 // There are four cases here.
9702 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009703 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009704 // there as appropriate.
9705 // Recover from invalid scope qualifiers as if they just weren't there.
9706 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009707 // C++0x [namespace.memdef]p3:
9708 // If the name in a friend declaration is neither qualified nor
9709 // a template-id and the declaration is a function or an
9710 // elaborated-type-specifier, the lookup to determine whether
9711 // the entity has been previously declared shall not consider
9712 // any scopes outside the innermost enclosing namespace.
9713 // C++0x [class.friend]p11:
9714 // If a friend declaration appears in a local class and the name
9715 // specified is an unqualified name, a prior declaration is
9716 // looked up without considering scopes that are outside the
9717 // innermost enclosing non-class scope. For a friend function
9718 // declaration, if there is no prior declaration, the program is
9719 // ill-formed.
9720 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009721 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009722
John McCall29ae6e52010-10-13 05:45:15 +00009723 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009724 DC = CurContext;
9725 while (true) {
9726 // Skip class contexts. If someone can cite chapter and verse
9727 // for this behavior, that would be nice --- it's what GCC and
9728 // EDG do, and it seems like a reasonable intent, but the spec
9729 // really only says that checks for unqualified existing
9730 // declarations should stop at the nearest enclosing namespace,
9731 // not that they should only consider the nearest enclosing
9732 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00009733 while (DC->isRecord())
9734 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00009735
John McCall68263142009-11-18 22:49:29 +00009736 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00009737
9738 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00009739 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00009740 break;
John McCall29ae6e52010-10-13 05:45:15 +00009741
John McCall8a407372010-10-14 22:22:28 +00009742 if (isTemplateId) {
9743 if (isa<TranslationUnitDecl>(DC)) break;
9744 } else {
9745 if (DC->isFileContext()) break;
9746 }
John McCall67d1a672009-08-06 02:15:43 +00009747 DC = DC->getParent();
9748 }
9749
9750 // C++ [class.friend]p1: A friend of a class is a function or
9751 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00009752 // C++0x changes this for both friend types and functions.
9753 // Most C++ 98 compilers do seem to give an error here, so
9754 // we do, too.
John McCall68263142009-11-18 22:49:29 +00009755 if (!Previous.empty() && DC->Equals(CurContext)
9756 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00009757 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00009758
John McCall380aaa42010-10-13 06:22:15 +00009759 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00009760
John McCall337ec3d2010-10-12 23:13:28 +00009761 // - There's a non-dependent scope specifier, in which case we
9762 // compute it and do a previous lookup there for a function
9763 // or function template.
9764 } else if (!SS.getScopeRep()->isDependent()) {
9765 DC = computeDeclContext(SS);
9766 if (!DC) return 0;
9767
9768 if (RequireCompleteDeclContext(SS, DC)) return 0;
9769
9770 LookupQualifiedName(Previous, DC);
9771
9772 // Ignore things found implicitly in the wrong scope.
9773 // TODO: better diagnostics for this case. Suggesting the right
9774 // qualified scope would be nice...
9775 LookupResult::Filter F = Previous.makeFilter();
9776 while (F.hasNext()) {
9777 NamedDecl *D = F.next();
9778 if (!DC->InEnclosingNamespaceSetOf(
9779 D->getDeclContext()->getRedeclContext()))
9780 F.erase();
9781 }
9782 F.done();
9783
9784 if (Previous.empty()) {
9785 D.setInvalidType();
9786 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9787 return 0;
9788 }
9789
9790 // C++ [class.friend]p1: A friend of a class is a function or
9791 // class that is not a member of the class . . .
9792 if (DC->Equals(CurContext))
9793 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9794
9795 // - There's a scope specifier that does not match any template
9796 // parameter lists, in which case we use some arbitrary context,
9797 // create a method or method template, and wait for instantiation.
9798 // - There's a scope specifier that does match some template
9799 // parameter lists, which we don't handle right now.
9800 } else {
9801 DC = CurContext;
9802 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00009803 }
9804
John McCall29ae6e52010-10-13 05:45:15 +00009805 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00009806 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009807 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9808 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9809 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00009810 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009811 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9812 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00009813 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009814 }
John McCall67d1a672009-08-06 02:15:43 +00009815 }
9816
Douglas Gregor182ddf02009-09-28 00:08:27 +00009817 bool Redeclaration = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009818 bool AddToScope = true;
John McCall380aaa42010-10-13 06:22:15 +00009819 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00009820 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00009821 IsDefinition,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009822 Redeclaration, AddToScope);
John McCalld226f652010-08-21 09:40:31 +00009823 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00009824
Douglas Gregor182ddf02009-09-28 00:08:27 +00009825 assert(ND->getDeclContext() == DC);
9826 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00009827
John McCallab88d972009-08-31 22:39:49 +00009828 // Add the function declaration to the appropriate lookup tables,
9829 // adjusting the redeclarations list as necessary. We don't
9830 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00009831 //
John McCallab88d972009-08-31 22:39:49 +00009832 // Also update the scope-based lookup if the target context's
9833 // lookup context is in lexical scope.
9834 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009835 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00009836 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009837 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00009838 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009839 }
John McCall02cace72009-08-28 07:59:38 +00009840
9841 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00009842 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00009843 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00009844 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00009845 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00009846
John McCall337ec3d2010-10-12 23:13:28 +00009847 if (ND->isInvalidDecl())
9848 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00009849 else {
9850 FunctionDecl *FD;
9851 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9852 FD = FTD->getTemplatedDecl();
9853 else
9854 FD = cast<FunctionDecl>(ND);
9855
9856 // Mark templated-scope function declarations as unsupported.
9857 if (FD->getNumTemplateParameterLists())
9858 FrD->setUnsupportedFriend(true);
9859 }
John McCall337ec3d2010-10-12 23:13:28 +00009860
John McCalld226f652010-08-21 09:40:31 +00009861 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00009862}
9863
John McCalld226f652010-08-21 09:40:31 +00009864void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9865 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00009866
Sebastian Redl50de12f2009-03-24 22:27:57 +00009867 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9868 if (!Fn) {
9869 Diag(DelLoc, diag::err_deleted_non_function);
9870 return;
9871 }
9872 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9873 Diag(DelLoc, diag::err_deleted_decl_not_first);
9874 Diag(Prev->getLocation(), diag::note_previous_declaration);
9875 // If the declaration wasn't the first, we delete the function anyway for
9876 // recovery.
9877 }
Sean Hunt10620eb2011-05-06 20:44:56 +00009878 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00009879}
Sebastian Redl13e88542009-04-27 21:33:24 +00009880
Sean Hunte4246a62011-05-12 06:15:49 +00009881void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9882 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9883
9884 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00009885 if (MD->getParent()->isDependentType()) {
9886 MD->setDefaulted();
9887 MD->setExplicitlyDefaulted();
9888 return;
9889 }
9890
Sean Hunte4246a62011-05-12 06:15:49 +00009891 CXXSpecialMember Member = getSpecialMember(MD);
9892 if (Member == CXXInvalid) {
9893 Diag(DefaultLoc, diag::err_default_special_members);
9894 return;
9895 }
9896
9897 MD->setDefaulted();
9898 MD->setExplicitlyDefaulted();
9899
Sean Huntcd10dec2011-05-23 23:14:04 +00009900 // If this definition appears within the record, do the checking when
9901 // the record is complete.
9902 const FunctionDecl *Primary = MD;
9903 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9904 // Find the uninstantiated declaration that actually had the '= default'
9905 // on it.
9906 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9907
9908 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00009909 return;
9910
9911 switch (Member) {
9912 case CXXDefaultConstructor: {
9913 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9914 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009915 if (!CD->isInvalidDecl())
9916 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9917 break;
9918 }
9919
9920 case CXXCopyConstructor: {
9921 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9922 CheckExplicitlyDefaultedCopyConstructor(CD);
9923 if (!CD->isInvalidDecl())
9924 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00009925 break;
9926 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00009927
Sean Hunt2b188082011-05-14 05:23:28 +00009928 case CXXCopyAssignment: {
9929 CheckExplicitlyDefaultedCopyAssignment(MD);
9930 if (!MD->isInvalidDecl())
9931 DefineImplicitCopyAssignment(DefaultLoc, MD);
9932 break;
9933 }
9934
Sean Huntcb45a0f2011-05-12 22:46:25 +00009935 case CXXDestructor: {
9936 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9937 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009938 if (!DD->isInvalidDecl())
9939 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009940 break;
9941 }
9942
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009943 case CXXMoveConstructor: {
9944 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9945 CheckExplicitlyDefaultedMoveConstructor(CD);
9946 if (!CD->isInvalidDecl())
9947 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +00009948 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009949 }
Sean Hunt82713172011-05-25 23:16:36 +00009950
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009951 case CXXMoveAssignment: {
9952 CheckExplicitlyDefaultedMoveAssignment(MD);
9953 if (!MD->isInvalidDecl())
9954 DefineImplicitMoveAssignment(DefaultLoc, MD);
9955 break;
9956 }
9957
9958 case CXXInvalid:
9959 assert(false && "Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +00009960 break;
9961 }
9962 } else {
9963 Diag(DefaultLoc, diag::err_default_special_members);
9964 }
9965}
9966
Sebastian Redl13e88542009-04-27 21:33:24 +00009967static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00009968 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00009969 Stmt *SubStmt = *CI;
9970 if (!SubStmt)
9971 continue;
9972 if (isa<ReturnStmt>(SubStmt))
9973 Self.Diag(SubStmt->getSourceRange().getBegin(),
9974 diag::err_return_in_constructor_handler);
9975 if (!isa<Expr>(SubStmt))
9976 SearchForReturnInStmt(Self, SubStmt);
9977 }
9978}
9979
9980void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9981 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9982 CXXCatchStmt *Handler = TryBlock->getHandler(I);
9983 SearchForReturnInStmt(*this, Handler);
9984 }
9985}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009986
Mike Stump1eb44332009-09-09 15:08:12 +00009987bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009988 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00009989 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
9990 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009991
Chandler Carruth73857792010-02-15 11:53:20 +00009992 if (Context.hasSameType(NewTy, OldTy) ||
9993 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009994 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00009995
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009996 // Check if the return types are covariant
9997 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00009998
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009999 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010000 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10001 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010002 NewClassTy = NewPT->getPointeeType();
10003 OldClassTy = OldPT->getPointeeType();
10004 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010005 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10006 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10007 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10008 NewClassTy = NewRT->getPointeeType();
10009 OldClassTy = OldRT->getPointeeType();
10010 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010011 }
10012 }
Mike Stump1eb44332009-09-09 15:08:12 +000010013
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010014 // The return types aren't either both pointers or references to a class type.
10015 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010016 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010017 diag::err_different_return_type_for_overriding_virtual_function)
10018 << New->getDeclName() << NewTy << OldTy;
10019 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010020
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010021 return true;
10022 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010023
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010024 // C++ [class.virtual]p6:
10025 // If the return type of D::f differs from the return type of B::f, the
10026 // class type in the return type of D::f shall be complete at the point of
10027 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010028 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10029 if (!RT->isBeingDefined() &&
10030 RequireCompleteType(New->getLocation(), NewClassTy,
10031 PDiag(diag::err_covariant_return_incomplete)
10032 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010033 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010034 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010035
Douglas Gregora4923eb2009-11-16 21:35:15 +000010036 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010037 // Check if the new class derives from the old class.
10038 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10039 Diag(New->getLocation(),
10040 diag::err_covariant_return_not_derived)
10041 << New->getDeclName() << NewTy << OldTy;
10042 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10043 return true;
10044 }
Mike Stump1eb44332009-09-09 15:08:12 +000010045
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010046 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010047 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010048 diag::err_covariant_return_inaccessible_base,
10049 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10050 // FIXME: Should this point to the return type?
10051 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010052 // FIXME: this note won't trigger for delayed access control
10053 // diagnostics, and it's impossible to get an undelayed error
10054 // here from access control during the original parse because
10055 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010056 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10057 return true;
10058 }
10059 }
Mike Stump1eb44332009-09-09 15:08:12 +000010060
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010061 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010062 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010063 Diag(New->getLocation(),
10064 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010065 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010066 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10067 return true;
10068 };
Mike Stump1eb44332009-09-09 15:08:12 +000010069
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010070
10071 // The new class type must have the same or less qualifiers as the old type.
10072 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10073 Diag(New->getLocation(),
10074 diag::err_covariant_return_type_class_type_more_qualified)
10075 << New->getDeclName() << NewTy << OldTy;
10076 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10077 return true;
10078 };
Mike Stump1eb44332009-09-09 15:08:12 +000010079
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010080 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010081}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010082
Douglas Gregor4ba31362009-12-01 17:24:26 +000010083/// \brief Mark the given method pure.
10084///
10085/// \param Method the method to be marked pure.
10086///
10087/// \param InitRange the source range that covers the "0" initializer.
10088bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010089 SourceLocation EndLoc = InitRange.getEnd();
10090 if (EndLoc.isValid())
10091 Method->setRangeEnd(EndLoc);
10092
Douglas Gregor4ba31362009-12-01 17:24:26 +000010093 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10094 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010095 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010096 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010097
10098 if (!Method->isInvalidDecl())
10099 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10100 << Method->getDeclName() << InitRange;
10101 return true;
10102}
10103
John McCall731ad842009-12-19 09:28:58 +000010104/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10105/// an initializer for the out-of-line declaration 'Dcl'. The scope
10106/// is a fresh scope pushed for just this purpose.
10107///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010108/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10109/// static data member of class X, names should be looked up in the scope of
10110/// class X.
John McCalld226f652010-08-21 09:40:31 +000010111void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010112 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010113 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010114
John McCall731ad842009-12-19 09:28:58 +000010115 // We should only get called for declarations with scope specifiers, like:
10116 // int foo::bar;
10117 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010118 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010119}
10120
10121/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010122/// initializer for the out-of-line declaration 'D'.
10123void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010124 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010125 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010126
John McCall731ad842009-12-19 09:28:58 +000010127 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010128 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010129}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010130
10131/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10132/// C++ if/switch/while/for statement.
10133/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010134DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010135 // C++ 6.4p2:
10136 // The declarator shall not specify a function or an array.
10137 // The type-specifier-seq shall not contain typedef and shall not declare a
10138 // new class or enumeration.
10139 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10140 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010141
10142 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010143 if (!Dcl)
10144 return true;
10145
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010146 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10147 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010148 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010149 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010150 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010151
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010152 return Dcl;
10153}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010154
Douglas Gregordfe65432011-07-28 19:11:31 +000010155void Sema::LoadExternalVTableUses() {
10156 if (!ExternalSource)
10157 return;
10158
10159 SmallVector<ExternalVTableUse, 4> VTables;
10160 ExternalSource->ReadUsedVTables(VTables);
10161 SmallVector<VTableUse, 4> NewUses;
10162 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10163 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10164 = VTablesUsed.find(VTables[I].Record);
10165 // Even if a definition wasn't required before, it may be required now.
10166 if (Pos != VTablesUsed.end()) {
10167 if (!Pos->second && VTables[I].DefinitionRequired)
10168 Pos->second = true;
10169 continue;
10170 }
10171
10172 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10173 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10174 }
10175
10176 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10177}
10178
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010179void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10180 bool DefinitionRequired) {
10181 // Ignore any vtable uses in unevaluated operands or for classes that do
10182 // not have a vtable.
10183 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10184 CurContext->isDependentContext() ||
10185 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010186 return;
10187
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010188 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010189 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010190 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10191 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10192 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10193 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010194 // If we already had an entry, check to see if we are promoting this vtable
10195 // to required a definition. If so, we need to reappend to the VTableUses
10196 // list, since we may have already processed the first entry.
10197 if (DefinitionRequired && !Pos.first->second) {
10198 Pos.first->second = true;
10199 } else {
10200 // Otherwise, we can early exit.
10201 return;
10202 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010203 }
10204
10205 // Local classes need to have their virtual members marked
10206 // immediately. For all other classes, we mark their virtual members
10207 // at the end of the translation unit.
10208 if (Class->isLocalClass())
10209 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010210 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010211 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010212}
10213
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010214bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010215 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010216 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010217 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010218
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010219 // Note: The VTableUses vector could grow as a result of marking
10220 // the members of a class as "used", so we check the size each
10221 // time through the loop and prefer indices (with are stable) to
10222 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010223 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010224 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010225 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010226 if (!Class)
10227 continue;
10228
10229 SourceLocation Loc = VTableUses[I].second;
10230
10231 // If this class has a key function, but that key function is
10232 // defined in another translation unit, we don't need to emit the
10233 // vtable even though we're using it.
10234 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010235 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010236 switch (KeyFunction->getTemplateSpecializationKind()) {
10237 case TSK_Undeclared:
10238 case TSK_ExplicitSpecialization:
10239 case TSK_ExplicitInstantiationDeclaration:
10240 // The key function is in another translation unit.
10241 continue;
10242
10243 case TSK_ExplicitInstantiationDefinition:
10244 case TSK_ImplicitInstantiation:
10245 // We will be instantiating the key function.
10246 break;
10247 }
10248 } else if (!KeyFunction) {
10249 // If we have a class with no key function that is the subject
10250 // of an explicit instantiation declaration, suppress the
10251 // vtable; it will live with the explicit instantiation
10252 // definition.
10253 bool IsExplicitInstantiationDeclaration
10254 = Class->getTemplateSpecializationKind()
10255 == TSK_ExplicitInstantiationDeclaration;
10256 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10257 REnd = Class->redecls_end();
10258 R != REnd; ++R) {
10259 TemplateSpecializationKind TSK
10260 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10261 if (TSK == TSK_ExplicitInstantiationDeclaration)
10262 IsExplicitInstantiationDeclaration = true;
10263 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10264 IsExplicitInstantiationDeclaration = false;
10265 break;
10266 }
10267 }
10268
10269 if (IsExplicitInstantiationDeclaration)
10270 continue;
10271 }
10272
10273 // Mark all of the virtual members of this class as referenced, so
10274 // that we can build a vtable. Then, tell the AST consumer that a
10275 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010276 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010277 MarkVirtualMembersReferenced(Loc, Class);
10278 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10279 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10280
10281 // Optionally warn if we're emitting a weak vtable.
10282 if (Class->getLinkage() == ExternalLinkage &&
10283 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010284 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010285 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10286 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010287 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010288 VTableUses.clear();
10289
Douglas Gregor78844032011-04-22 22:25:37 +000010290 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010291}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010292
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010293void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10294 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010295 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10296 e = RD->method_end(); i != e; ++i) {
10297 CXXMethodDecl *MD = *i;
10298
10299 // C++ [basic.def.odr]p2:
10300 // [...] A virtual member function is used if it is not pure. [...]
10301 if (MD->isVirtual() && !MD->isPure())
10302 MarkDeclarationReferenced(Loc, MD);
10303 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010304
10305 // Only classes that have virtual bases need a VTT.
10306 if (RD->getNumVBases() == 0)
10307 return;
10308
10309 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10310 e = RD->bases_end(); i != e; ++i) {
10311 const CXXRecordDecl *Base =
10312 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010313 if (Base->getNumVBases() == 0)
10314 continue;
10315 MarkVirtualMembersReferenced(Loc, Base);
10316 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010317}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010318
10319/// SetIvarInitializers - This routine builds initialization ASTs for the
10320/// Objective-C implementation whose ivars need be initialized.
10321void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10322 if (!getLangOptions().CPlusPlus)
10323 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010324 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010325 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010326 CollectIvarsToConstructOrDestruct(OID, ivars);
10327 if (ivars.empty())
10328 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010329 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010330 for (unsigned i = 0; i < ivars.size(); i++) {
10331 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010332 if (Field->isInvalidDecl())
10333 continue;
10334
Sean Huntcbb67482011-01-08 20:30:50 +000010335 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010336 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10337 InitializationKind InitKind =
10338 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10339
10340 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010341 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010342 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010343 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010344 // Note, MemberInit could actually come back empty if no initialization
10345 // is required (e.g., because it would call a trivial default constructor)
10346 if (!MemberInit.get() || MemberInit.isInvalid())
10347 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010348
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010349 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010350 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10351 SourceLocation(),
10352 MemberInit.takeAs<Expr>(),
10353 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010354 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010355
10356 // Be sure that the destructor is accessible and is marked as referenced.
10357 if (const RecordType *RecordTy
10358 = Context.getBaseElementType(Field->getType())
10359 ->getAs<RecordType>()) {
10360 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010361 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010362 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10363 CheckDestructorAccess(Field->getLocation(), Destructor,
10364 PDiag(diag::err_access_dtor_ivar)
10365 << Context.getBaseElementType(Field->getType()));
10366 }
10367 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010368 }
10369 ObjCImplementation->setIvarInitializers(Context,
10370 AllToInit.data(), AllToInit.size());
10371 }
10372}
Sean Huntfe57eef2011-05-04 05:57:24 +000010373
Sean Huntebcbe1d2011-05-04 23:29:54 +000010374static
10375void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10376 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10377 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10378 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10379 Sema &S) {
10380 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10381 CE = Current.end();
10382 if (Ctor->isInvalidDecl())
10383 return;
10384
10385 const FunctionDecl *FNTarget = 0;
10386 CXXConstructorDecl *Target;
10387
10388 // We ignore the result here since if we don't have a body, Target will be
10389 // null below.
10390 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10391 Target
10392= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10393
10394 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10395 // Avoid dereferencing a null pointer here.
10396 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10397
10398 if (!Current.insert(Canonical))
10399 return;
10400
10401 // We know that beyond here, we aren't chaining into a cycle.
10402 if (!Target || !Target->isDelegatingConstructor() ||
10403 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10404 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10405 Valid.insert(*CI);
10406 Current.clear();
10407 // We've hit a cycle.
10408 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10409 Current.count(TCanonical)) {
10410 // If we haven't diagnosed this cycle yet, do so now.
10411 if (!Invalid.count(TCanonical)) {
10412 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010413 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010414 << Ctor;
10415
10416 // Don't add a note for a function delegating directo to itself.
10417 if (TCanonical != Canonical)
10418 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10419
10420 CXXConstructorDecl *C = Target;
10421 while (C->getCanonicalDecl() != Canonical) {
10422 (void)C->getTargetConstructor()->hasBody(FNTarget);
10423 assert(FNTarget && "Ctor cycle through bodiless function");
10424
10425 C
10426 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10427 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10428 }
10429 }
10430
10431 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10432 Invalid.insert(*CI);
10433 Current.clear();
10434 } else {
10435 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10436 }
10437}
10438
10439
Sean Huntfe57eef2011-05-04 05:57:24 +000010440void Sema::CheckDelegatingCtorCycles() {
10441 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10442
Sean Huntebcbe1d2011-05-04 23:29:54 +000010443 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10444 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010445
Douglas Gregor0129b562011-07-27 21:57:17 +000010446 for (DelegatingCtorDeclsType::iterator
10447 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010448 E = DelegatingCtorDecls.end();
10449 I != E; ++I) {
10450 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010451 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010452
10453 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10454 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010455}