blob: 9ffb7765af180e8cdad5d8d0c4422d5feeca6672 [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.
Richard Trieu90ab75b2011-09-09 03:18:59 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **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,
Richard Trieu90ab75b2011-09-09 03:18:59 +00002706 CXXCtorInitializer **meminits,
2707 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002708 bool AnyErrors) {
2709 if (!ConstructorDecl)
2710 return;
2711
2712 AdjustDeclIfTemplate(ConstructorDecl);
2713
2714 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002715 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002716
2717 if (!Constructor) {
2718 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2719 return;
2720 }
2721
Sean Huntcbb67482011-01-08 20:30:50 +00002722 CXXCtorInitializer **MemInits =
2723 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002724
2725 // Mapping for the duplicate initializers check.
2726 // For member initializers, this is keyed with a FieldDecl*.
2727 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002728 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002729
2730 // Mapping for the inconsistent anonymous-union initializers check.
2731 RedundantUnionMap MemberUnions;
2732
Anders Carlssonea356fb2010-04-02 05:42:15 +00002733 bool HadError = false;
2734 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002735 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002736
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002737 // Set the source order index.
2738 Init->setSourceOrder(i);
2739
Francois Pichet00eb3f92010-12-04 09:14:42 +00002740 if (Init->isAnyMemberInitializer()) {
2741 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002742 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2743 CheckRedundantUnionInit(*this, Init, MemberUnions))
2744 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002745 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002746 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2747 if (CheckRedundantInit(*this, Init, Members[Key]))
2748 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002749 } else {
2750 assert(Init->isDelegatingInitializer());
2751 // This must be the only initializer
2752 if (i != 0 || NumMemInits > 1) {
2753 Diag(MemInits[0]->getSourceLocation(),
2754 diag::err_delegating_initializer_alone)
2755 << MemInits[0]->getSourceRange();
2756 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002757 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002758 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002759 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002760 // Return immediately as the initializer is set.
2761 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002762 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002763 }
2764
Anders Carlssonea356fb2010-04-02 05:42:15 +00002765 if (HadError)
2766 return;
2767
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002768 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002769
Sean Huntcbb67482011-01-08 20:30:50 +00002770 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002771}
2772
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002773void
John McCallef027fe2010-03-16 21:39:52 +00002774Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2775 CXXRecordDecl *ClassDecl) {
2776 // Ignore dependent contexts.
2777 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002778 return;
John McCall58e6f342010-03-16 05:22:47 +00002779
2780 // FIXME: all the access-control diagnostics are positioned on the
2781 // field/base declaration. That's probably good; that said, the
2782 // user might reasonably want to know why the destructor is being
2783 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002784
Anders Carlsson9f853df2009-11-17 04:44:12 +00002785 // Non-static data members.
2786 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2787 E = ClassDecl->field_end(); I != E; ++I) {
2788 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002789 if (Field->isInvalidDecl())
2790 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002791 QualType FieldType = Context.getBaseElementType(Field->getType());
2792
2793 const RecordType* RT = FieldType->getAs<RecordType>();
2794 if (!RT)
2795 continue;
2796
2797 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002798 if (FieldClassDecl->isInvalidDecl())
2799 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002800 if (FieldClassDecl->hasTrivialDestructor())
2801 continue;
2802
Douglas Gregordb89f282010-07-01 22:47:18 +00002803 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002804 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002805 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002806 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002807 << Field->getDeclName()
2808 << FieldType);
2809
John McCallef027fe2010-03-16 21:39:52 +00002810 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002811 }
2812
John McCall58e6f342010-03-16 05:22:47 +00002813 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2814
Anders Carlsson9f853df2009-11-17 04:44:12 +00002815 // Bases.
2816 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2817 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002818 // Bases are always records in a well-formed non-dependent class.
2819 const RecordType *RT = Base->getType()->getAs<RecordType>();
2820
2821 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002822 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002823 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002824
John McCall58e6f342010-03-16 05:22:47 +00002825 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002826 // If our base class is invalid, we probably can't get its dtor anyway.
2827 if (BaseClassDecl->isInvalidDecl())
2828 continue;
2829 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002830 if (BaseClassDecl->hasTrivialDestructor())
2831 continue;
John McCall58e6f342010-03-16 05:22:47 +00002832
Douglas Gregordb89f282010-07-01 22:47:18 +00002833 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002834 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002835
2836 // FIXME: caret should be on the start of the class name
2837 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002838 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002839 << Base->getType()
2840 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002841
John McCallef027fe2010-03-16 21:39:52 +00002842 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002843 }
2844
2845 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002846 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2847 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002848
2849 // Bases are always records in a well-formed non-dependent class.
2850 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2851
2852 // Ignore direct virtual bases.
2853 if (DirectVirtualBases.count(RT))
2854 continue;
2855
John McCall58e6f342010-03-16 05:22:47 +00002856 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002857 // If our base class is invalid, we probably can't get its dtor anyway.
2858 if (BaseClassDecl->isInvalidDecl())
2859 continue;
2860 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002861 if (BaseClassDecl->hasTrivialDestructor())
2862 continue;
John McCall58e6f342010-03-16 05:22:47 +00002863
Douglas Gregordb89f282010-07-01 22:47:18 +00002864 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002865 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002866 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002867 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002868 << VBase->getType());
2869
John McCallef027fe2010-03-16 21:39:52 +00002870 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002871 }
2872}
2873
John McCalld226f652010-08-21 09:40:31 +00002874void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002875 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002876 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002877
Mike Stump1eb44332009-09-09 15:08:12 +00002878 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002879 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002880 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002881}
2882
Mike Stump1eb44332009-09-09 15:08:12 +00002883bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002884 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002885 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002886 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002887 else
John McCall94c3b562010-08-18 09:41:07 +00002888 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002889}
2890
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002891bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002892 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002893 if (!getLangOptions().CPlusPlus)
2894 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Anders Carlsson11f21a02009-03-23 19:10:31 +00002896 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002897 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002898
Ted Kremenek6217b802009-07-29 21:53:49 +00002899 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002900 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002901 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002902 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002903
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002904 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002905 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002906 }
Mike Stump1eb44332009-09-09 15:08:12 +00002907
Ted Kremenek6217b802009-07-29 21:53:49 +00002908 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002909 if (!RT)
2910 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002911
John McCall86ff3082010-02-04 22:26:26 +00002912 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002913
John McCall94c3b562010-08-18 09:41:07 +00002914 // We can't answer whether something is abstract until it has a
2915 // definition. If it's currently being defined, we'll walk back
2916 // over all the declarations when we have a full definition.
2917 const CXXRecordDecl *Def = RD->getDefinition();
2918 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002919 return false;
2920
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002921 if (!RD->isAbstract())
2922 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002924 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002925 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002926
John McCall94c3b562010-08-18 09:41:07 +00002927 return true;
2928}
2929
2930void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2931 // Check if we've already emitted the list of pure virtual functions
2932 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002933 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002934 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002936 CXXFinalOverriderMap FinalOverriders;
2937 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002938
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002939 // Keep a set of seen pure methods so we won't diagnose the same method
2940 // more than once.
2941 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2942
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002943 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2944 MEnd = FinalOverriders.end();
2945 M != MEnd;
2946 ++M) {
2947 for (OverridingMethods::iterator SO = M->second.begin(),
2948 SOEnd = M->second.end();
2949 SO != SOEnd; ++SO) {
2950 // C++ [class.abstract]p4:
2951 // A class is abstract if it contains or inherits at least one
2952 // pure virtual function for which the final overrider is pure
2953 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002954
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002955 //
2956 if (SO->second.size() != 1)
2957 continue;
2958
2959 if (!SO->second.front().Method->isPure())
2960 continue;
2961
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002962 if (!SeenPureMethods.insert(SO->second.front().Method))
2963 continue;
2964
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002965 Diag(SO->second.front().Method->getLocation(),
2966 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002967 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002968 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002969 }
2970
2971 if (!PureVirtualClassDiagSet)
2972 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2973 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002974}
2975
Anders Carlsson8211eff2009-03-24 01:19:16 +00002976namespace {
John McCall94c3b562010-08-18 09:41:07 +00002977struct AbstractUsageInfo {
2978 Sema &S;
2979 CXXRecordDecl *Record;
2980 CanQualType AbstractType;
2981 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002982
John McCall94c3b562010-08-18 09:41:07 +00002983 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2984 : S(S), Record(Record),
2985 AbstractType(S.Context.getCanonicalType(
2986 S.Context.getTypeDeclType(Record))),
2987 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002988
John McCall94c3b562010-08-18 09:41:07 +00002989 void DiagnoseAbstractType() {
2990 if (Invalid) return;
2991 S.DiagnoseAbstractType(Record);
2992 Invalid = true;
2993 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002994
John McCall94c3b562010-08-18 09:41:07 +00002995 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2996};
2997
2998struct CheckAbstractUsage {
2999 AbstractUsageInfo &Info;
3000 const NamedDecl *Ctx;
3001
3002 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3003 : Info(Info), Ctx(Ctx) {}
3004
3005 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3006 switch (TL.getTypeLocClass()) {
3007#define ABSTRACT_TYPELOC(CLASS, PARENT)
3008#define TYPELOC(CLASS, PARENT) \
3009 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3010#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003011 }
John McCall94c3b562010-08-18 09:41:07 +00003012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
John McCall94c3b562010-08-18 09:41:07 +00003014 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3015 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3016 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003017 if (!TL.getArg(I))
3018 continue;
3019
John McCall94c3b562010-08-18 09:41:07 +00003020 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3021 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003022 }
John McCall94c3b562010-08-18 09:41:07 +00003023 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003024
John McCall94c3b562010-08-18 09:41:07 +00003025 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3026 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3027 }
Mike Stump1eb44332009-09-09 15:08:12 +00003028
John McCall94c3b562010-08-18 09:41:07 +00003029 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3030 // Visit the type parameters from a permissive context.
3031 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3032 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3033 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3034 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3035 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3036 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003037 }
John McCall94c3b562010-08-18 09:41:07 +00003038 }
Mike Stump1eb44332009-09-09 15:08:12 +00003039
John McCall94c3b562010-08-18 09:41:07 +00003040 // Visit pointee types from a permissive context.
3041#define CheckPolymorphic(Type) \
3042 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3043 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3044 }
3045 CheckPolymorphic(PointerTypeLoc)
3046 CheckPolymorphic(ReferenceTypeLoc)
3047 CheckPolymorphic(MemberPointerTypeLoc)
3048 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003049
John McCall94c3b562010-08-18 09:41:07 +00003050 /// Handle all the types we haven't given a more specific
3051 /// implementation for above.
3052 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3053 // Every other kind of type that we haven't called out already
3054 // that has an inner type is either (1) sugar or (2) contains that
3055 // inner type in some way as a subobject.
3056 if (TypeLoc Next = TL.getNextTypeLoc())
3057 return Visit(Next, Sel);
3058
3059 // If there's no inner type and we're in a permissive context,
3060 // don't diagnose.
3061 if (Sel == Sema::AbstractNone) return;
3062
3063 // Check whether the type matches the abstract type.
3064 QualType T = TL.getType();
3065 if (T->isArrayType()) {
3066 Sel = Sema::AbstractArrayType;
3067 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003068 }
John McCall94c3b562010-08-18 09:41:07 +00003069 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3070 if (CT != Info.AbstractType) return;
3071
3072 // It matched; do some magic.
3073 if (Sel == Sema::AbstractArrayType) {
3074 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3075 << T << TL.getSourceRange();
3076 } else {
3077 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3078 << Sel << T << TL.getSourceRange();
3079 }
3080 Info.DiagnoseAbstractType();
3081 }
3082};
3083
3084void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3085 Sema::AbstractDiagSelID Sel) {
3086 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3087}
3088
3089}
3090
3091/// Check for invalid uses of an abstract type in a method declaration.
3092static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3093 CXXMethodDecl *MD) {
3094 // No need to do the check on definitions, which require that
3095 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003096 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003097 return;
3098
3099 // For safety's sake, just ignore it if we don't have type source
3100 // information. This should never happen for non-implicit methods,
3101 // but...
3102 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3103 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3104}
3105
3106/// Check for invalid uses of an abstract type within a class definition.
3107static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3108 CXXRecordDecl *RD) {
3109 for (CXXRecordDecl::decl_iterator
3110 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3111 Decl *D = *I;
3112 if (D->isImplicit()) continue;
3113
3114 // Methods and method templates.
3115 if (isa<CXXMethodDecl>(D)) {
3116 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3117 } else if (isa<FunctionTemplateDecl>(D)) {
3118 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3119 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3120
3121 // Fields and static variables.
3122 } else if (isa<FieldDecl>(D)) {
3123 FieldDecl *FD = cast<FieldDecl>(D);
3124 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3125 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3126 } else if (isa<VarDecl>(D)) {
3127 VarDecl *VD = cast<VarDecl>(D);
3128 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3129 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3130
3131 // Nested classes and class templates.
3132 } else if (isa<CXXRecordDecl>(D)) {
3133 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3134 } else if (isa<ClassTemplateDecl>(D)) {
3135 CheckAbstractClassUsage(Info,
3136 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3137 }
3138 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003139}
3140
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003141/// \brief Perform semantic checks on a class definition that has been
3142/// completing, introducing implicitly-declared members, checking for
3143/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003144void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003145 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003146 return;
3147
John McCall94c3b562010-08-18 09:41:07 +00003148 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3149 AbstractUsageInfo Info(*this, Record);
3150 CheckAbstractClassUsage(Info, Record);
3151 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003152
3153 // If this is not an aggregate type and has no user-declared constructor,
3154 // complain about any non-static data members of reference or const scalar
3155 // type, since they will never get initializers.
3156 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3157 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3158 bool Complained = false;
3159 for (RecordDecl::field_iterator F = Record->field_begin(),
3160 FEnd = Record->field_end();
3161 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003162 if (F->hasInClassInitializer())
3163 continue;
3164
Douglas Gregor325e5932010-04-15 00:00:53 +00003165 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003166 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003167 if (!Complained) {
3168 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3169 << Record->getTagKind() << Record;
3170 Complained = true;
3171 }
3172
3173 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3174 << F->getType()->isReferenceType()
3175 << F->getDeclName();
3176 }
3177 }
3178 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003179
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003180 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003181 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003182
3183 if (Record->getIdentifier()) {
3184 // C++ [class.mem]p13:
3185 // If T is the name of a class, then each of the following shall have a
3186 // name different from T:
3187 // - every member of every anonymous union that is a member of class T.
3188 //
3189 // C++ [class.mem]p14:
3190 // In addition, if class T has a user-declared constructor (12.1), every
3191 // non-static data member of class T shall have a name different from T.
3192 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003193 R.first != R.second; ++R.first) {
3194 NamedDecl *D = *R.first;
3195 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3196 isa<IndirectFieldDecl>(D)) {
3197 Diag(D->getLocation(), diag::err_member_name_of_class)
3198 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003199 break;
3200 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003201 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003202 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003203
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003204 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003205 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003206 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003207 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003208 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3209 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3210 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003211
3212 // See if a method overloads virtual methods in a base
3213 /// class without overriding any.
3214 if (!Record->isDependentType()) {
3215 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3216 MEnd = Record->method_end();
3217 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003218 if (!(*M)->isStatic())
3219 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003220 }
3221 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003222
3223 // Declare inherited constructors. We do this eagerly here because:
3224 // - The standard requires an eager diagnostic for conflicting inherited
3225 // constructors from different classes.
3226 // - The lazy declaration of the other implicit constructors is so as to not
3227 // waste space and performance on classes that are not meant to be
3228 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3229 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003230 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003231
Sean Hunteb88ae52011-05-23 21:07:59 +00003232 if (!Record->isDependentType())
3233 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003234}
3235
3236void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003237 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3238 ME = Record->method_end();
3239 MI != ME; ++MI) {
3240 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3241 switch (getSpecialMember(*MI)) {
3242 case CXXDefaultConstructor:
3243 CheckExplicitlyDefaultedDefaultConstructor(
3244 cast<CXXConstructorDecl>(*MI));
3245 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003246
Sean Huntcb45a0f2011-05-12 22:46:25 +00003247 case CXXDestructor:
3248 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3249 break;
3250
3251 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003252 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3253 break;
3254
Sean Huntcb45a0f2011-05-12 22:46:25 +00003255 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003256 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003257 break;
3258
Sean Hunt82713172011-05-25 23:16:36 +00003259 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003260 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003261 break;
3262
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003263 case CXXMoveAssignment:
3264 CheckExplicitlyDefaultedMoveAssignment(*MI);
3265 break;
3266
3267 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003268 llvm_unreachable("non-special member explicitly defaulted!");
3269 }
Sean Hunt001cad92011-05-10 00:49:42 +00003270 }
3271 }
3272
Sean Hunt001cad92011-05-10 00:49:42 +00003273}
3274
3275void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3276 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3277
3278 // Whether this was the first-declared instance of the constructor.
3279 // This affects whether we implicitly add an exception spec (and, eventually,
3280 // constexpr). It is also ill-formed to explicitly default a constructor such
3281 // that it would be deleted. (C++0x [decl.fct.def.default])
3282 bool First = CD == CD->getCanonicalDecl();
3283
Sean Hunt49634cf2011-05-13 06:10:58 +00003284 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003285 if (CD->getNumParams() != 0) {
3286 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3287 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003288 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003289 }
3290
3291 ImplicitExceptionSpecification Spec
3292 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3293 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003294 if (EPI.ExceptionSpecType == EST_Delayed) {
3295 // Exception specification depends on some deferred part of the class. We'll
3296 // try again when the class's definition has been fully processed.
3297 return;
3298 }
Sean Hunt001cad92011-05-10 00:49:42 +00003299 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3300 *ExceptionType = Context.getFunctionType(
3301 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3302
3303 if (CtorType->hasExceptionSpec()) {
3304 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003305 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003306 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003307 PDiag(),
3308 ExceptionType, SourceLocation(),
3309 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003310 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003311 }
3312 } else if (First) {
3313 // We set the declaration to have the computed exception spec here.
3314 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003315 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003316 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3317 }
Sean Huntca46d132011-05-12 03:51:48 +00003318
Sean Hunt49634cf2011-05-13 06:10:58 +00003319 if (HadError) {
3320 CD->setInvalidDecl();
3321 return;
3322 }
3323
Sean Huntca46d132011-05-12 03:51:48 +00003324 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003325 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003326 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003327 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003328 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003329 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003330 CD->setInvalidDecl();
3331 }
3332 }
3333}
3334
3335void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3336 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3337
3338 // Whether this was the first-declared instance of the constructor.
3339 bool First = CD == CD->getCanonicalDecl();
3340
3341 bool HadError = false;
3342 if (CD->getNumParams() != 1) {
3343 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3344 << CD->getSourceRange();
3345 HadError = true;
3346 }
3347
3348 ImplicitExceptionSpecification Spec(Context);
3349 bool Const;
3350 llvm::tie(Spec, Const) =
3351 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3352
3353 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3354 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3355 *ExceptionType = Context.getFunctionType(
3356 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3357
3358 // Check for parameter type matching.
3359 // This is a copy ctor so we know it's a cv-qualified reference to T.
3360 QualType ArgType = CtorType->getArgType(0);
3361 if (ArgType->getPointeeType().isVolatileQualified()) {
3362 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3363 HadError = true;
3364 }
3365 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3366 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3367 HadError = true;
3368 }
3369
3370 if (CtorType->hasExceptionSpec()) {
3371 if (CheckEquivalentExceptionSpec(
3372 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003373 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003374 PDiag(),
3375 ExceptionType, SourceLocation(),
3376 CtorType, CD->getLocation())) {
3377 HadError = true;
3378 }
3379 } else if (First) {
3380 // We set the declaration to have the computed exception spec here.
3381 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003382 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003383 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3384 }
3385
3386 if (HadError) {
3387 CD->setInvalidDecl();
3388 return;
3389 }
3390
3391 if (ShouldDeleteCopyConstructor(CD)) {
3392 if (First) {
3393 CD->setDeletedAsWritten();
3394 } else {
3395 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003396 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003397 CD->setInvalidDecl();
3398 }
Sean Huntca46d132011-05-12 03:51:48 +00003399 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003400}
Sean Hunt001cad92011-05-10 00:49:42 +00003401
Sean Hunt2b188082011-05-14 05:23:28 +00003402void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3403 assert(MD->isExplicitlyDefaulted());
3404
3405 // Whether this was the first-declared instance of the operator
3406 bool First = MD == MD->getCanonicalDecl();
3407
3408 bool HadError = false;
3409 if (MD->getNumParams() != 1) {
3410 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3411 << MD->getSourceRange();
3412 HadError = true;
3413 }
3414
3415 QualType ReturnType =
3416 MD->getType()->getAs<FunctionType>()->getResultType();
3417 if (!ReturnType->isLValueReferenceType() ||
3418 !Context.hasSameType(
3419 Context.getCanonicalType(ReturnType->getPointeeType()),
3420 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3421 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3422 HadError = true;
3423 }
3424
3425 ImplicitExceptionSpecification Spec(Context);
3426 bool Const;
3427 llvm::tie(Spec, Const) =
3428 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3429
3430 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3431 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3432 *ExceptionType = Context.getFunctionType(
3433 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3434
Sean Hunt2b188082011-05-14 05:23:28 +00003435 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003436 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003437 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003438 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003439 } else {
3440 if (ArgType->getPointeeType().isVolatileQualified()) {
3441 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3442 HadError = true;
3443 }
3444 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3445 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3446 HadError = true;
3447 }
Sean Hunt2b188082011-05-14 05:23:28 +00003448 }
Sean Huntbe631222011-05-17 20:44:43 +00003449
Sean Hunt2b188082011-05-14 05:23:28 +00003450 if (OperType->getTypeQuals()) {
3451 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3452 HadError = true;
3453 }
3454
3455 if (OperType->hasExceptionSpec()) {
3456 if (CheckEquivalentExceptionSpec(
3457 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003458 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003459 PDiag(),
3460 ExceptionType, SourceLocation(),
3461 OperType, MD->getLocation())) {
3462 HadError = true;
3463 }
3464 } else if (First) {
3465 // We set the declaration to have the computed exception spec here.
3466 // We duplicate the one parameter type.
3467 EPI.RefQualifier = OperType->getRefQualifier();
3468 EPI.ExtInfo = OperType->getExtInfo();
3469 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3470 }
3471
3472 if (HadError) {
3473 MD->setInvalidDecl();
3474 return;
3475 }
3476
3477 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3478 if (First) {
3479 MD->setDeletedAsWritten();
3480 } else {
3481 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003482 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003483 MD->setInvalidDecl();
3484 }
3485 }
3486}
3487
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003488void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3489 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3490
3491 // Whether this was the first-declared instance of the constructor.
3492 bool First = CD == CD->getCanonicalDecl();
3493
3494 bool HadError = false;
3495 if (CD->getNumParams() != 1) {
3496 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3497 << CD->getSourceRange();
3498 HadError = true;
3499 }
3500
3501 ImplicitExceptionSpecification Spec(
3502 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3503
3504 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3505 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3506 *ExceptionType = Context.getFunctionType(
3507 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3508
3509 // Check for parameter type matching.
3510 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3511 QualType ArgType = CtorType->getArgType(0);
3512 if (ArgType->getPointeeType().isVolatileQualified()) {
3513 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3514 HadError = true;
3515 }
3516 if (ArgType->getPointeeType().isConstQualified()) {
3517 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3518 HadError = true;
3519 }
3520
3521 if (CtorType->hasExceptionSpec()) {
3522 if (CheckEquivalentExceptionSpec(
3523 PDiag(diag::err_incorrect_defaulted_exception_spec)
3524 << CXXMoveConstructor,
3525 PDiag(),
3526 ExceptionType, SourceLocation(),
3527 CtorType, CD->getLocation())) {
3528 HadError = true;
3529 }
3530 } else if (First) {
3531 // We set the declaration to have the computed exception spec here.
3532 // We duplicate the one parameter type.
3533 EPI.ExtInfo = CtorType->getExtInfo();
3534 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3535 }
3536
3537 if (HadError) {
3538 CD->setInvalidDecl();
3539 return;
3540 }
3541
3542 if (ShouldDeleteMoveConstructor(CD)) {
3543 if (First) {
3544 CD->setDeletedAsWritten();
3545 } else {
3546 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3547 << CXXMoveConstructor;
3548 CD->setInvalidDecl();
3549 }
3550 }
3551}
3552
3553void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3554 assert(MD->isExplicitlyDefaulted());
3555
3556 // Whether this was the first-declared instance of the operator
3557 bool First = MD == MD->getCanonicalDecl();
3558
3559 bool HadError = false;
3560 if (MD->getNumParams() != 1) {
3561 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3562 << MD->getSourceRange();
3563 HadError = true;
3564 }
3565
3566 QualType ReturnType =
3567 MD->getType()->getAs<FunctionType>()->getResultType();
3568 if (!ReturnType->isLValueReferenceType() ||
3569 !Context.hasSameType(
3570 Context.getCanonicalType(ReturnType->getPointeeType()),
3571 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3572 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3573 HadError = true;
3574 }
3575
3576 ImplicitExceptionSpecification Spec(
3577 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3578
3579 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3580 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3581 *ExceptionType = Context.getFunctionType(
3582 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3583
3584 QualType ArgType = OperType->getArgType(0);
3585 if (!ArgType->isRValueReferenceType()) {
3586 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3587 HadError = true;
3588 } else {
3589 if (ArgType->getPointeeType().isVolatileQualified()) {
3590 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3591 HadError = true;
3592 }
3593 if (ArgType->getPointeeType().isConstQualified()) {
3594 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3595 HadError = true;
3596 }
3597 }
3598
3599 if (OperType->getTypeQuals()) {
3600 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3601 HadError = true;
3602 }
3603
3604 if (OperType->hasExceptionSpec()) {
3605 if (CheckEquivalentExceptionSpec(
3606 PDiag(diag::err_incorrect_defaulted_exception_spec)
3607 << CXXMoveAssignment,
3608 PDiag(),
3609 ExceptionType, SourceLocation(),
3610 OperType, MD->getLocation())) {
3611 HadError = true;
3612 }
3613 } else if (First) {
3614 // We set the declaration to have the computed exception spec here.
3615 // We duplicate the one parameter type.
3616 EPI.RefQualifier = OperType->getRefQualifier();
3617 EPI.ExtInfo = OperType->getExtInfo();
3618 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3619 }
3620
3621 if (HadError) {
3622 MD->setInvalidDecl();
3623 return;
3624 }
3625
3626 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3627 if (First) {
3628 MD->setDeletedAsWritten();
3629 } else {
3630 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3631 << CXXMoveAssignment;
3632 MD->setInvalidDecl();
3633 }
3634 }
3635}
3636
Sean Huntcb45a0f2011-05-12 22:46:25 +00003637void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3638 assert(DD->isExplicitlyDefaulted());
3639
3640 // Whether this was the first-declared instance of the destructor.
3641 bool First = DD == DD->getCanonicalDecl();
3642
3643 ImplicitExceptionSpecification Spec
3644 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3645 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3646 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3647 *ExceptionType = Context.getFunctionType(
3648 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3649
3650 if (DtorType->hasExceptionSpec()) {
3651 if (CheckEquivalentExceptionSpec(
3652 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003653 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003654 PDiag(),
3655 ExceptionType, SourceLocation(),
3656 DtorType, DD->getLocation())) {
3657 DD->setInvalidDecl();
3658 return;
3659 }
3660 } else if (First) {
3661 // We set the declaration to have the computed exception spec here.
3662 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003663 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003664 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3665 }
3666
3667 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003668 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003669 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003670 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003671 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003672 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003673 DD->setInvalidDecl();
3674 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003675 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003676}
3677
Sean Huntcdee3fe2011-05-11 22:34:38 +00003678bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3679 CXXRecordDecl *RD = CD->getParent();
3680 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003681 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003682 return false;
3683
Sean Hunt71a682f2011-05-18 03:41:58 +00003684 SourceLocation Loc = CD->getLocation();
3685
Sean Huntcdee3fe2011-05-11 22:34:38 +00003686 // Do access control from the constructor
3687 ContextRAII CtorContext(*this, CD);
3688
3689 bool Union = RD->isUnion();
3690 bool AllConst = true;
3691
Sean Huntcdee3fe2011-05-11 22:34:38 +00003692 // We do this because we should never actually use an anonymous
3693 // union's constructor.
3694 if (Union && RD->isAnonymousStructOrUnion())
3695 return false;
3696
3697 // FIXME: We should put some diagnostic logic right into this function.
3698
3699 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003700 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003701
3702 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3703 BE = RD->bases_end();
3704 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003705 // We'll handle this one later
3706 if (BI->isVirtual())
3707 continue;
3708
Sean Huntcdee3fe2011-05-11 22:34:38 +00003709 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3710 assert(BaseDecl && "base isn't a CXXRecordDecl");
3711
3712 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003713 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003714 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3715 if (BaseDtor->isDeleted())
3716 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003717 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003718 AR_accessible)
3719 return true;
3720
Sean Huntcdee3fe2011-05-11 22:34:38 +00003721 // -- any [direct base class either] has no default constructor or
3722 // overload resolution as applied to [its] default constructor
3723 // results in an ambiguity or in a function that is deleted or
3724 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003725 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3726 if (!BaseDefault || BaseDefault->isDeleted())
3727 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003728
Sean Huntb320e0c2011-06-10 03:50:41 +00003729 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3730 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003731 return true;
3732 }
3733
3734 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3735 BE = RD->vbases_end();
3736 BI != BE; ++BI) {
3737 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3738 assert(BaseDecl && "base isn't a CXXRecordDecl");
3739
3740 // -- any [virtual base class] has a type with a destructor that is
3741 // delete or inaccessible from the defaulted default constructor
3742 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3743 if (BaseDtor->isDeleted())
3744 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003745 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003746 AR_accessible)
3747 return true;
3748
3749 // -- any [virtual base class either] has no default constructor or
3750 // overload resolution as applied to [its] default constructor
3751 // results in an ambiguity or in a function that is deleted or
3752 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003753 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3754 if (!BaseDefault || BaseDefault->isDeleted())
3755 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003756
Sean Huntb320e0c2011-06-10 03:50:41 +00003757 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3758 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003759 return true;
3760 }
3761
3762 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3763 FE = RD->field_end();
3764 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003765 if (FI->isInvalidDecl())
3766 continue;
3767
Sean Huntcdee3fe2011-05-11 22:34:38 +00003768 QualType FieldType = Context.getBaseElementType(FI->getType());
3769 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003770
Sean Huntcdee3fe2011-05-11 22:34:38 +00003771 // -- any non-static data member with no brace-or-equal-initializer is of
3772 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003773 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003774 return true;
3775
3776 // -- X is a union and all its variant members are of const-qualified type
3777 // (or array thereof)
3778 if (Union && !FieldType.isConstQualified())
3779 AllConst = false;
3780
3781 if (FieldRecord) {
3782 // -- X is a union-like class that has a variant member with a non-trivial
3783 // default constructor
3784 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3785 return true;
3786
3787 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3788 if (FieldDtor->isDeleted())
3789 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003790 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003791 AR_accessible)
3792 return true;
3793
3794 // -- any non-variant non-static data member of const-qualified type (or
3795 // array thereof) with no brace-or-equal-initializer does not have a
3796 // user-provided default constructor
3797 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003798 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003799 !FieldRecord->hasUserProvidedDefaultConstructor())
3800 return true;
3801
3802 if (!Union && FieldRecord->isUnion() &&
3803 FieldRecord->isAnonymousStructOrUnion()) {
3804 // We're okay to reuse AllConst here since we only care about the
3805 // value otherwise if we're in a union.
3806 AllConst = true;
3807
3808 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3809 UE = FieldRecord->field_end();
3810 UI != UE; ++UI) {
3811 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3812 CXXRecordDecl *UnionFieldRecord =
3813 UnionFieldType->getAsCXXRecordDecl();
3814
3815 if (!UnionFieldType.isConstQualified())
3816 AllConst = false;
3817
3818 if (UnionFieldRecord &&
3819 !UnionFieldRecord->hasTrivialDefaultConstructor())
3820 return true;
3821 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003822
Sean Huntcdee3fe2011-05-11 22:34:38 +00003823 if (AllConst)
3824 return true;
3825
3826 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003827 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003828 continue;
3829 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003830
Richard Smith7a614d82011-06-11 17:19:42 +00003831 // -- any non-static data member with no brace-or-equal-initializer has
3832 // class type M (or array thereof) and either M has no default
3833 // constructor or overload resolution as applied to M's default
3834 // constructor results in an ambiguity or in a function that is deleted
3835 // or inaccessible from the defaulted default constructor.
3836 if (!FI->hasInClassInitializer()) {
3837 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3838 if (!FieldDefault || FieldDefault->isDeleted())
3839 return true;
3840 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3841 PDiag()) != AR_accessible)
3842 return true;
3843 }
3844 } else if (!Union && FieldType.isConstQualified() &&
3845 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003846 // -- any non-variant non-static data member of const-qualified type (or
3847 // array thereof) with no brace-or-equal-initializer does not have a
3848 // user-provided default constructor
3849 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003850 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003851 }
3852
3853 if (Union && AllConst)
3854 return true;
3855
3856 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003857}
3858
Sean Hunt49634cf2011-05-13 06:10:58 +00003859bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003860 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003861 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003862 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003863 return false;
3864
Sean Hunt71a682f2011-05-18 03:41:58 +00003865 SourceLocation Loc = CD->getLocation();
3866
Sean Hunt49634cf2011-05-13 06:10:58 +00003867 // Do access control from the constructor
3868 ContextRAII CtorContext(*this, CD);
3869
Sean Huntc530d172011-06-10 04:44:37 +00003870 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003871
Sean Hunt2b188082011-05-14 05:23:28 +00003872 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3873 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003874 unsigned ArgQuals =
3875 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3876 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003877
3878 // We do this because we should never actually use an anonymous
3879 // union's constructor.
3880 if (Union && RD->isAnonymousStructOrUnion())
3881 return false;
3882
3883 // FIXME: We should put some diagnostic logic right into this function.
3884
3885 // C++0x [class.copy]/11
3886 // A defaulted [copy] constructor for class X is defined as delete if X has:
3887
3888 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3889 BE = RD->bases_end();
3890 BI != BE; ++BI) {
3891 // We'll handle this one later
3892 if (BI->isVirtual())
3893 continue;
3894
3895 QualType BaseType = BI->getType();
3896 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3897 assert(BaseDecl && "base isn't a CXXRecordDecl");
3898
3899 // -- any [direct base class] of a type with a destructor that is deleted or
3900 // inaccessible from the defaulted constructor
3901 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3902 if (BaseDtor->isDeleted())
3903 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003904 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003905 AR_accessible)
3906 return true;
3907
3908 // -- a [direct base class] B that cannot be [copied] because overload
3909 // resolution, as applied to B's [copy] constructor, results in an
3910 // ambiguity or a function that is deleted or inaccessible from the
3911 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003912 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003913 if (!BaseCtor || BaseCtor->isDeleted())
3914 return true;
3915 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3916 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003917 return true;
3918 }
3919
3920 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3921 BE = RD->vbases_end();
3922 BI != BE; ++BI) {
3923 QualType BaseType = BI->getType();
3924 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3925 assert(BaseDecl && "base isn't a CXXRecordDecl");
3926
Sean Huntb320e0c2011-06-10 03:50:41 +00003927 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003928 // inaccessible from the defaulted constructor
3929 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3930 if (BaseDtor->isDeleted())
3931 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003932 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003933 AR_accessible)
3934 return true;
3935
3936 // -- a [virtual base class] B that cannot be [copied] because overload
3937 // resolution, as applied to B's [copy] constructor, results in an
3938 // ambiguity or a function that is deleted or inaccessible from the
3939 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003940 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003941 if (!BaseCtor || BaseCtor->isDeleted())
3942 return true;
3943 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3944 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003945 return true;
3946 }
3947
3948 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3949 FE = RD->field_end();
3950 FI != FE; ++FI) {
3951 QualType FieldType = Context.getBaseElementType(FI->getType());
3952
3953 // -- for a copy constructor, a non-static data member of rvalue reference
3954 // type
3955 if (FieldType->isRValueReferenceType())
3956 return true;
3957
3958 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3959
3960 if (FieldRecord) {
3961 // This is an anonymous union
3962 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3963 // Anonymous unions inside unions do not variant members create
3964 if (!Union) {
3965 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3966 UE = FieldRecord->field_end();
3967 UI != UE; ++UI) {
3968 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3969 CXXRecordDecl *UnionFieldRecord =
3970 UnionFieldType->getAsCXXRecordDecl();
3971
3972 // -- a variant member with a non-trivial [copy] constructor and X
3973 // is a union-like class
3974 if (UnionFieldRecord &&
3975 !UnionFieldRecord->hasTrivialCopyConstructor())
3976 return true;
3977 }
3978 }
3979
3980 // Don't try to initalize an anonymous union
3981 continue;
3982 } else {
3983 // -- a variant member with a non-trivial [copy] constructor and X is a
3984 // union-like class
3985 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3986 return true;
3987
3988 // -- any [non-static data member] of a type with a destructor that is
3989 // deleted or inaccessible from the defaulted constructor
3990 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3991 if (FieldDtor->isDeleted())
3992 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003993 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003994 AR_accessible)
3995 return true;
3996 }
Sean Huntc530d172011-06-10 04:44:37 +00003997
3998 // -- a [non-static data member of class type (or array thereof)] B that
3999 // cannot be [copied] because overload resolution, as applied to B's
4000 // [copy] constructor, results in an ambiguity or a function that is
4001 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00004002 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4003 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00004004 if (!FieldCtor || FieldCtor->isDeleted())
4005 return true;
4006 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4007 PDiag()) != AR_accessible)
4008 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00004009 }
Sean Hunt49634cf2011-05-13 06:10:58 +00004010 }
4011
4012 return false;
4013}
4014
Sean Hunt7f410192011-05-14 05:23:24 +00004015bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4016 CXXRecordDecl *RD = MD->getParent();
4017 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004018 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004019 return false;
4020
Sean Hunt71a682f2011-05-18 03:41:58 +00004021 SourceLocation Loc = MD->getLocation();
4022
Sean Hunt7f410192011-05-14 05:23:24 +00004023 // Do access control from the constructor
4024 ContextRAII MethodContext(*this, MD);
4025
4026 bool Union = RD->isUnion();
4027
Sean Hunt661c67a2011-06-21 23:42:56 +00004028 unsigned ArgQuals =
4029 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4030 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004031
4032 // We do this because we should never actually use an anonymous
4033 // union's constructor.
4034 if (Union && RD->isAnonymousStructOrUnion())
4035 return false;
4036
Sean Hunt7f410192011-05-14 05:23:24 +00004037 // FIXME: We should put some diagnostic logic right into this function.
4038
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004039 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004040 // A defaulted [copy] assignment operator for class X is defined as deleted
4041 // if X has:
4042
4043 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4044 BE = RD->bases_end();
4045 BI != BE; ++BI) {
4046 // We'll handle this one later
4047 if (BI->isVirtual())
4048 continue;
4049
4050 QualType BaseType = BI->getType();
4051 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4052 assert(BaseDecl && "base isn't a CXXRecordDecl");
4053
4054 // -- a [direct base class] B that cannot be [copied] because overload
4055 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004056 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004057 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004058 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4059 0);
4060 if (!CopyOper || CopyOper->isDeleted())
4061 return true;
4062 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004063 return true;
4064 }
4065
4066 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4067 BE = RD->vbases_end();
4068 BI != BE; ++BI) {
4069 QualType BaseType = BI->getType();
4070 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4071 assert(BaseDecl && "base isn't a CXXRecordDecl");
4072
Sean Hunt7f410192011-05-14 05:23:24 +00004073 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004074 // resolution, as applied to B's [copy] assignment operator, results in
4075 // an ambiguity or a function that is deleted or inaccessible from the
4076 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004077 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4078 0);
4079 if (!CopyOper || CopyOper->isDeleted())
4080 return true;
4081 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004082 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004083 }
4084
4085 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4086 FE = RD->field_end();
4087 FI != FE; ++FI) {
4088 QualType FieldType = Context.getBaseElementType(FI->getType());
4089
4090 // -- a non-static data member of reference type
4091 if (FieldType->isReferenceType())
4092 return true;
4093
4094 // -- a non-static data member of const non-class type (or array thereof)
4095 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4096 return true;
4097
4098 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4099
4100 if (FieldRecord) {
4101 // This is an anonymous union
4102 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4103 // Anonymous unions inside unions do not variant members create
4104 if (!Union) {
4105 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4106 UE = FieldRecord->field_end();
4107 UI != UE; ++UI) {
4108 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4109 CXXRecordDecl *UnionFieldRecord =
4110 UnionFieldType->getAsCXXRecordDecl();
4111
4112 // -- a variant member with a non-trivial [copy] assignment operator
4113 // and X is a union-like class
4114 if (UnionFieldRecord &&
4115 !UnionFieldRecord->hasTrivialCopyAssignment())
4116 return true;
4117 }
4118 }
4119
4120 // Don't try to initalize an anonymous union
4121 continue;
4122 // -- a variant member with a non-trivial [copy] assignment operator
4123 // and X is a union-like class
4124 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4125 return true;
4126 }
Sean Hunt7f410192011-05-14 05:23:24 +00004127
Sean Hunt661c67a2011-06-21 23:42:56 +00004128 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4129 false, 0);
4130 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004131 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004132 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004133 return true;
4134 }
4135 }
4136
4137 return false;
4138}
4139
4140bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4141 CXXRecordDecl *RD = CD->getParent();
4142 assert(!RD->isDependentType() && "do deletion after instantiation");
4143 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4144 return false;
4145
4146 SourceLocation Loc = CD->getLocation();
4147
4148 // Do access control from the constructor
4149 ContextRAII CtorContext(*this, CD);
4150
4151 bool Union = RD->isUnion();
4152
4153 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4154 "copy assignment arg has no pointee type");
4155
4156 // We do this because we should never actually use an anonymous
4157 // union's constructor.
4158 if (Union && RD->isAnonymousStructOrUnion())
4159 return false;
4160
4161 // C++0x [class.copy]/11
4162 // A defaulted [move] constructor for class X is defined as deleted
4163 // if X has:
4164
4165 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4166 BE = RD->bases_end();
4167 BI != BE; ++BI) {
4168 // We'll handle this one later
4169 if (BI->isVirtual())
4170 continue;
4171
4172 QualType BaseType = BI->getType();
4173 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4174 assert(BaseDecl && "base isn't a CXXRecordDecl");
4175
4176 // -- any [direct base class] of a type with a destructor that is deleted or
4177 // inaccessible from the defaulted constructor
4178 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4179 if (BaseDtor->isDeleted())
4180 return true;
4181 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4182 AR_accessible)
4183 return true;
4184
4185 // -- a [direct base class] B that cannot be [moved] because overload
4186 // resolution, as applied to B's [move] constructor, results in an
4187 // ambiguity or a function that is deleted or inaccessible from the
4188 // defaulted constructor
4189 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4190 if (!BaseCtor || BaseCtor->isDeleted())
4191 return true;
4192 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4193 AR_accessible)
4194 return true;
4195
4196 // -- for a move constructor, a [direct base class] with a type that
4197 // does not have a move constructor and is not trivially copyable.
4198 // If the field isn't a record, it's always trivially copyable.
4199 // A moving constructor could be a copy constructor instead.
4200 if (!BaseCtor->isMoveConstructor() &&
4201 !BaseDecl->isTriviallyCopyable())
4202 return true;
4203 }
4204
4205 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4206 BE = RD->vbases_end();
4207 BI != BE; ++BI) {
4208 QualType BaseType = BI->getType();
4209 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4210 assert(BaseDecl && "base isn't a CXXRecordDecl");
4211
4212 // -- any [virtual base class] of a type with a destructor that is deleted
4213 // or inaccessible from the defaulted constructor
4214 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4215 if (BaseDtor->isDeleted())
4216 return true;
4217 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4218 AR_accessible)
4219 return true;
4220
4221 // -- a [virtual base class] B that cannot be [moved] because overload
4222 // resolution, as applied to B's [move] constructor, results in an
4223 // ambiguity or a function that is deleted or inaccessible from the
4224 // defaulted constructor
4225 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4226 if (!BaseCtor || BaseCtor->isDeleted())
4227 return true;
4228 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4229 AR_accessible)
4230 return true;
4231
4232 // -- for a move constructor, a [virtual base class] with a type that
4233 // does not have a move constructor and is not trivially copyable.
4234 // If the field isn't a record, it's always trivially copyable.
4235 // A moving constructor could be a copy constructor instead.
4236 if (!BaseCtor->isMoveConstructor() &&
4237 !BaseDecl->isTriviallyCopyable())
4238 return true;
4239 }
4240
4241 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4242 FE = RD->field_end();
4243 FI != FE; ++FI) {
4244 QualType FieldType = Context.getBaseElementType(FI->getType());
4245
4246 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4247 // This is an anonymous union
4248 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4249 // Anonymous unions inside unions do not variant members create
4250 if (!Union) {
4251 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4252 UE = FieldRecord->field_end();
4253 UI != UE; ++UI) {
4254 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4255 CXXRecordDecl *UnionFieldRecord =
4256 UnionFieldType->getAsCXXRecordDecl();
4257
4258 // -- a variant member with a non-trivial [move] constructor and X
4259 // is a union-like class
4260 if (UnionFieldRecord &&
4261 !UnionFieldRecord->hasTrivialMoveConstructor())
4262 return true;
4263 }
4264 }
4265
4266 // Don't try to initalize an anonymous union
4267 continue;
4268 } else {
4269 // -- a variant member with a non-trivial [move] constructor and X is a
4270 // union-like class
4271 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4272 return true;
4273
4274 // -- any [non-static data member] of a type with a destructor that is
4275 // deleted or inaccessible from the defaulted constructor
4276 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4277 if (FieldDtor->isDeleted())
4278 return true;
4279 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4280 AR_accessible)
4281 return true;
4282 }
4283
4284 // -- a [non-static data member of class type (or array thereof)] B that
4285 // cannot be [moved] because overload resolution, as applied to B's
4286 // [move] constructor, results in an ambiguity or a function that is
4287 // deleted or inaccessible from the defaulted constructor
4288 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4289 if (!FieldCtor || FieldCtor->isDeleted())
4290 return true;
4291 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4292 PDiag()) != AR_accessible)
4293 return true;
4294
4295 // -- for a move constructor, a [non-static data member] with a type that
4296 // does not have a move constructor and is not trivially copyable.
4297 // If the field isn't a record, it's always trivially copyable.
4298 // A moving constructor could be a copy constructor instead.
4299 if (!FieldCtor->isMoveConstructor() &&
4300 !FieldRecord->isTriviallyCopyable())
4301 return true;
4302 }
4303 }
4304
4305 return false;
4306}
4307
4308bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4309 CXXRecordDecl *RD = MD->getParent();
4310 assert(!RD->isDependentType() && "do deletion after instantiation");
4311 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4312 return false;
4313
4314 SourceLocation Loc = MD->getLocation();
4315
4316 // Do access control from the constructor
4317 ContextRAII MethodContext(*this, MD);
4318
4319 bool Union = RD->isUnion();
4320
4321 // We do this because we should never actually use an anonymous
4322 // union's constructor.
4323 if (Union && RD->isAnonymousStructOrUnion())
4324 return false;
4325
4326 // C++0x [class.copy]/20
4327 // A defaulted [move] assignment operator for class X is defined as deleted
4328 // if X has:
4329
4330 // -- for the move constructor, [...] any direct or indirect virtual base
4331 // class.
4332 if (RD->getNumVBases() != 0)
4333 return true;
4334
4335 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4336 BE = RD->bases_end();
4337 BI != BE; ++BI) {
4338
4339 QualType BaseType = BI->getType();
4340 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4341 assert(BaseDecl && "base isn't a CXXRecordDecl");
4342
4343 // -- a [direct base class] B that cannot be [moved] because overload
4344 // resolution, as applied to B's [move] assignment operator, results in
4345 // an ambiguity or a function that is deleted or inaccessible from the
4346 // assignment operator
4347 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4348 if (!MoveOper || MoveOper->isDeleted())
4349 return true;
4350 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4351 return true;
4352
4353 // -- for the move assignment operator, a [direct base class] with a type
4354 // that does not have a move assignment operator and is not trivially
4355 // copyable.
4356 if (!MoveOper->isMoveAssignmentOperator() &&
4357 !BaseDecl->isTriviallyCopyable())
4358 return true;
4359 }
4360
4361 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4362 FE = RD->field_end();
4363 FI != FE; ++FI) {
4364 QualType FieldType = Context.getBaseElementType(FI->getType());
4365
4366 // -- a non-static data member of reference type
4367 if (FieldType->isReferenceType())
4368 return true;
4369
4370 // -- a non-static data member of const non-class type (or array thereof)
4371 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4372 return true;
4373
4374 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4375
4376 if (FieldRecord) {
4377 // This is an anonymous union
4378 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4379 // Anonymous unions inside unions do not variant members create
4380 if (!Union) {
4381 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4382 UE = FieldRecord->field_end();
4383 UI != UE; ++UI) {
4384 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4385 CXXRecordDecl *UnionFieldRecord =
4386 UnionFieldType->getAsCXXRecordDecl();
4387
4388 // -- a variant member with a non-trivial [move] assignment operator
4389 // and X is a union-like class
4390 if (UnionFieldRecord &&
4391 !UnionFieldRecord->hasTrivialMoveAssignment())
4392 return true;
4393 }
4394 }
4395
4396 // Don't try to initalize an anonymous union
4397 continue;
4398 // -- a variant member with a non-trivial [move] assignment operator
4399 // and X is a union-like class
4400 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4401 return true;
4402 }
4403
4404 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4405 if (!MoveOper || MoveOper->isDeleted())
4406 return true;
4407 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4408 return true;
4409
4410 // -- for the move assignment operator, a [non-static data member] with a
4411 // type that does not have a move assignment operator and is not
4412 // trivially copyable.
4413 if (!MoveOper->isMoveAssignmentOperator() &&
4414 !FieldRecord->isTriviallyCopyable())
4415 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004416 }
Sean Hunt7f410192011-05-14 05:23:24 +00004417 }
4418
4419 return false;
4420}
4421
Sean Huntcb45a0f2011-05-12 22:46:25 +00004422bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4423 CXXRecordDecl *RD = DD->getParent();
4424 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004425 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004426 return false;
4427
Sean Hunt71a682f2011-05-18 03:41:58 +00004428 SourceLocation Loc = DD->getLocation();
4429
Sean Huntcb45a0f2011-05-12 22:46:25 +00004430 // Do access control from the destructor
4431 ContextRAII CtorContext(*this, DD);
4432
4433 bool Union = RD->isUnion();
4434
Sean Hunt49634cf2011-05-13 06:10:58 +00004435 // We do this because we should never actually use an anonymous
4436 // union's destructor.
4437 if (Union && RD->isAnonymousStructOrUnion())
4438 return false;
4439
Sean Huntcb45a0f2011-05-12 22:46:25 +00004440 // C++0x [class.dtor]p5
4441 // A defaulted destructor for a class X is defined as deleted if:
4442 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4443 BE = RD->bases_end();
4444 BI != BE; ++BI) {
4445 // We'll handle this one later
4446 if (BI->isVirtual())
4447 continue;
4448
4449 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4450 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4451 assert(BaseDtor && "base has no destructor");
4452
4453 // -- any direct or virtual base class has a deleted destructor or
4454 // a destructor that is inaccessible from the defaulted destructor
4455 if (BaseDtor->isDeleted())
4456 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004457 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004458 AR_accessible)
4459 return true;
4460 }
4461
4462 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4463 BE = RD->vbases_end();
4464 BI != BE; ++BI) {
4465 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4466 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4467 assert(BaseDtor && "base has no destructor");
4468
4469 // -- any direct or virtual base class has a deleted destructor or
4470 // a destructor that is inaccessible from the defaulted destructor
4471 if (BaseDtor->isDeleted())
4472 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004473 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004474 AR_accessible)
4475 return true;
4476 }
4477
4478 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4479 FE = RD->field_end();
4480 FI != FE; ++FI) {
4481 QualType FieldType = Context.getBaseElementType(FI->getType());
4482 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4483 if (FieldRecord) {
4484 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4485 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4486 UE = FieldRecord->field_end();
4487 UI != UE; ++UI) {
4488 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4489 CXXRecordDecl *UnionFieldRecord =
4490 UnionFieldType->getAsCXXRecordDecl();
4491
4492 // -- X is a union-like class that has a variant member with a non-
4493 // trivial destructor.
4494 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4495 return true;
4496 }
4497 // Technically we are supposed to do this next check unconditionally.
4498 // But that makes absolutely no sense.
4499 } else {
4500 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4501
4502 // -- any of the non-static data members has class type M (or array
4503 // thereof) and M has a deleted destructor or a destructor that is
4504 // inaccessible from the defaulted destructor
4505 if (FieldDtor->isDeleted())
4506 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004507 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004508 AR_accessible)
4509 return true;
4510
4511 // -- X is a union-like class that has a variant member with a non-
4512 // trivial destructor.
4513 if (Union && !FieldDtor->isTrivial())
4514 return true;
4515 }
4516 }
4517 }
4518
4519 if (DD->isVirtual()) {
4520 FunctionDecl *OperatorDelete = 0;
4521 DeclarationName Name =
4522 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004523 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004524 false))
4525 return true;
4526 }
4527
4528
4529 return false;
4530}
4531
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004532/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004533namespace {
4534 struct FindHiddenVirtualMethodData {
4535 Sema *S;
4536 CXXMethodDecl *Method;
4537 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004538 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004539 };
4540}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004541
4542/// \brief Member lookup function that determines whether a given C++
4543/// method overloads virtual methods in a base class without overriding any,
4544/// to be used with CXXRecordDecl::lookupInBases().
4545static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4546 CXXBasePath &Path,
4547 void *UserData) {
4548 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4549
4550 FindHiddenVirtualMethodData &Data
4551 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4552
4553 DeclarationName Name = Data.Method->getDeclName();
4554 assert(Name.getNameKind() == DeclarationName::Identifier);
4555
4556 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004557 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004558 for (Path.Decls = BaseRecord->lookup(Name);
4559 Path.Decls.first != Path.Decls.second;
4560 ++Path.Decls.first) {
4561 NamedDecl *D = *Path.Decls.first;
4562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004563 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004564 foundSameNameMethod = true;
4565 // Interested only in hidden virtual methods.
4566 if (!MD->isVirtual())
4567 continue;
4568 // If the method we are checking overrides a method from its base
4569 // don't warn about the other overloaded methods.
4570 if (!Data.S->IsOverload(Data.Method, MD, false))
4571 return true;
4572 // Collect the overload only if its hidden.
4573 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4574 overloadedMethods.push_back(MD);
4575 }
4576 }
4577
4578 if (foundSameNameMethod)
4579 Data.OverloadedMethods.append(overloadedMethods.begin(),
4580 overloadedMethods.end());
4581 return foundSameNameMethod;
4582}
4583
4584/// \brief See if a method overloads virtual methods in a base class without
4585/// overriding any.
4586void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4587 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4588 MD->getLocation()) == Diagnostic::Ignored)
4589 return;
4590 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4591 return;
4592
4593 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4594 /*bool RecordPaths=*/false,
4595 /*bool DetectVirtual=*/false);
4596 FindHiddenVirtualMethodData Data;
4597 Data.Method = MD;
4598 Data.S = this;
4599
4600 // Keep the base methods that were overriden or introduced in the subclass
4601 // by 'using' in a set. A base method not in this set is hidden.
4602 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4603 res.first != res.second; ++res.first) {
4604 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4605 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4606 E = MD->end_overridden_methods();
4607 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004608 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004609 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4610 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004611 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004612 }
4613
4614 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4615 !Data.OverloadedMethods.empty()) {
4616 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4617 << MD << (Data.OverloadedMethods.size() > 1);
4618
4619 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4620 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4621 Diag(overloadedMD->getLocation(),
4622 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4623 }
4624 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004625}
4626
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004627void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004628 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004629 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004630 SourceLocation RBrac,
4631 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004632 if (!TagDecl)
4633 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004634
Douglas Gregor42af25f2009-05-11 19:58:34 +00004635 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004636
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004637 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004638 // strict aliasing violation!
4639 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004640 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004641
Douglas Gregor23c94db2010-07-02 17:43:08 +00004642 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004643 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004644}
4645
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004646/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4647/// special functions, such as the default constructor, copy
4648/// constructor, or destructor, to the given C++ class (C++
4649/// [special]p1). This routine can only be executed just before the
4650/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004651void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004652 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004653 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004654
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004655 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004656 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004657
Douglas Gregora376d102010-07-02 21:50:04 +00004658 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4659 ++ASTContext::NumImplicitCopyAssignmentOperators;
4660
4661 // If we have a dynamic class, then the copy assignment operator may be
4662 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4663 // it shows up in the right place in the vtable and that we diagnose
4664 // problems with the implicit exception specification.
4665 if (ClassDecl->isDynamicClass())
4666 DeclareImplicitCopyAssignment(ClassDecl);
4667 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004668
Douglas Gregor4923aa22010-07-02 20:37:36 +00004669 if (!ClassDecl->hasUserDeclaredDestructor()) {
4670 ++ASTContext::NumImplicitDestructors;
4671
4672 // If we have a dynamic class, then the destructor may be virtual, so we
4673 // have to declare the destructor immediately. This ensures that, e.g., it
4674 // shows up in the right place in the vtable and that we diagnose problems
4675 // with the implicit exception specification.
4676 if (ClassDecl->isDynamicClass())
4677 DeclareImplicitDestructor(ClassDecl);
4678 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004679}
4680
Francois Pichet8387e2a2011-04-22 22:18:13 +00004681void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4682 if (!D)
4683 return;
4684
4685 int NumParamList = D->getNumTemplateParameterLists();
4686 for (int i = 0; i < NumParamList; i++) {
4687 TemplateParameterList* Params = D->getTemplateParameterList(i);
4688 for (TemplateParameterList::iterator Param = Params->begin(),
4689 ParamEnd = Params->end();
4690 Param != ParamEnd; ++Param) {
4691 NamedDecl *Named = cast<NamedDecl>(*Param);
4692 if (Named->getDeclName()) {
4693 S->AddDecl(Named);
4694 IdResolver.AddDecl(Named);
4695 }
4696 }
4697 }
4698}
4699
John McCalld226f652010-08-21 09:40:31 +00004700void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004701 if (!D)
4702 return;
4703
4704 TemplateParameterList *Params = 0;
4705 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4706 Params = Template->getTemplateParameters();
4707 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4708 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4709 Params = PartialSpec->getTemplateParameters();
4710 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004711 return;
4712
Douglas Gregor6569d682009-05-27 23:11:45 +00004713 for (TemplateParameterList::iterator Param = Params->begin(),
4714 ParamEnd = Params->end();
4715 Param != ParamEnd; ++Param) {
4716 NamedDecl *Named = cast<NamedDecl>(*Param);
4717 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004718 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004719 IdResolver.AddDecl(Named);
4720 }
4721 }
4722}
4723
John McCalld226f652010-08-21 09:40:31 +00004724void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004725 if (!RecordD) return;
4726 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004727 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004728 PushDeclContext(S, Record);
4729}
4730
John McCalld226f652010-08-21 09:40:31 +00004731void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004732 if (!RecordD) return;
4733 PopDeclContext();
4734}
4735
Douglas Gregor72b505b2008-12-16 21:30:33 +00004736/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4737/// parsing a top-level (non-nested) C++ class, and we are now
4738/// parsing those parts of the given Method declaration that could
4739/// not be parsed earlier (C++ [class.mem]p2), such as default
4740/// arguments. This action should enter the scope of the given
4741/// Method declaration as if we had just parsed the qualified method
4742/// name. However, it should not bring the parameters into scope;
4743/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004744void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004745}
4746
4747/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4748/// C++ method declaration. We're (re-)introducing the given
4749/// function parameter into scope for use in parsing later parts of
4750/// the method declaration. For example, we could see an
4751/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004752void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004753 if (!ParamD)
4754 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004755
John McCalld226f652010-08-21 09:40:31 +00004756 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004757
4758 // If this parameter has an unparsed default argument, clear it out
4759 // to make way for the parsed default argument.
4760 if (Param->hasUnparsedDefaultArg())
4761 Param->setDefaultArg(0);
4762
John McCalld226f652010-08-21 09:40:31 +00004763 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004764 if (Param->getDeclName())
4765 IdResolver.AddDecl(Param);
4766}
4767
4768/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4769/// processing the delayed method declaration for Method. The method
4770/// declaration is now considered finished. There may be a separate
4771/// ActOnStartOfFunctionDef action later (not necessarily
4772/// immediately!) for this method, if it was also defined inside the
4773/// class body.
John McCalld226f652010-08-21 09:40:31 +00004774void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004775 if (!MethodD)
4776 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004777
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004778 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004779
John McCalld226f652010-08-21 09:40:31 +00004780 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004781
4782 // Now that we have our default arguments, check the constructor
4783 // again. It could produce additional diagnostics or affect whether
4784 // the class has implicitly-declared destructors, among other
4785 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004786 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4787 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004788
4789 // Check the default arguments, which we may have added.
4790 if (!Method->isInvalidDecl())
4791 CheckCXXDefaultArguments(Method);
4792}
4793
Douglas Gregor42a552f2008-11-05 20:51:48 +00004794/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004795/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004796/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004797/// emit diagnostics and set the invalid bit to true. In any case, the type
4798/// will be updated to reflect a well-formed type for the constructor and
4799/// returned.
4800QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004801 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004802 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004803
4804 // C++ [class.ctor]p3:
4805 // A constructor shall not be virtual (10.3) or static (9.4). A
4806 // constructor can be invoked for a const, volatile or const
4807 // volatile object. A constructor shall not be declared const,
4808 // volatile, or const volatile (9.3.2).
4809 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004810 if (!D.isInvalidType())
4811 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4812 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4813 << SourceRange(D.getIdentifierLoc());
4814 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004815 }
John McCalld931b082010-08-26 03:08:43 +00004816 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004817 if (!D.isInvalidType())
4818 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4819 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4820 << SourceRange(D.getIdentifierLoc());
4821 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004822 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004823 }
Mike Stump1eb44332009-09-09 15:08:12 +00004824
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004825 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004826 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004827 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004828 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4829 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004830 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004831 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4832 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004833 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004834 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4835 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004836 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004837 }
Mike Stump1eb44332009-09-09 15:08:12 +00004838
Douglas Gregorc938c162011-01-26 05:01:58 +00004839 // C++0x [class.ctor]p4:
4840 // A constructor shall not be declared with a ref-qualifier.
4841 if (FTI.hasRefQualifier()) {
4842 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4843 << FTI.RefQualifierIsLValueRef
4844 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4845 D.setInvalidType();
4846 }
4847
Douglas Gregor42a552f2008-11-05 20:51:48 +00004848 // Rebuild the function type "R" without any type qualifiers (in
4849 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004850 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004851 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004852 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4853 return R;
4854
4855 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4856 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004857 EPI.RefQualifier = RQ_None;
4858
Chris Lattner65401802009-04-25 08:28:21 +00004859 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004860 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004861}
4862
Douglas Gregor72b505b2008-12-16 21:30:33 +00004863/// CheckConstructor - Checks a fully-formed constructor for
4864/// well-formedness, issuing any diagnostics required. Returns true if
4865/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004866void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004867 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004868 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4869 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004870 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004871
4872 // C++ [class.copy]p3:
4873 // A declaration of a constructor for a class X is ill-formed if
4874 // its first parameter is of type (optionally cv-qualified) X and
4875 // either there are no other parameters or else all other
4876 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004877 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004878 ((Constructor->getNumParams() == 1) ||
4879 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004880 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4881 Constructor->getTemplateSpecializationKind()
4882 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004883 QualType ParamType = Constructor->getParamDecl(0)->getType();
4884 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4885 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004886 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004887 const char *ConstRef
4888 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4889 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004890 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004891 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004892
4893 // FIXME: Rather that making the constructor invalid, we should endeavor
4894 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004895 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004896 }
4897 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004898}
4899
John McCall15442822010-08-04 01:04:25 +00004900/// CheckDestructor - Checks a fully-formed destructor definition for
4901/// well-formedness, issuing any diagnostics required. Returns true
4902/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004903bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004904 CXXRecordDecl *RD = Destructor->getParent();
4905
4906 if (Destructor->isVirtual()) {
4907 SourceLocation Loc;
4908
4909 if (!Destructor->isImplicit())
4910 Loc = Destructor->getLocation();
4911 else
4912 Loc = RD->getLocation();
4913
4914 // If we have a virtual destructor, look up the deallocation function
4915 FunctionDecl *OperatorDelete = 0;
4916 DeclarationName Name =
4917 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004918 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004919 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004920
4921 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004922
4923 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004924 }
Anders Carlsson37909802009-11-30 21:24:50 +00004925
4926 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004927}
4928
Mike Stump1eb44332009-09-09 15:08:12 +00004929static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004930FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4931 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4932 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004933 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004934}
4935
Douglas Gregor42a552f2008-11-05 20:51:48 +00004936/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4937/// the well-formednes of the destructor declarator @p D with type @p
4938/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004939/// emit diagnostics and set the declarator to invalid. Even if this happens,
4940/// will be updated to reflect a well-formed type for the destructor and
4941/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004942QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004943 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004944 // C++ [class.dtor]p1:
4945 // [...] A typedef-name that names a class is a class-name
4946 // (7.1.3); however, a typedef-name that names a class shall not
4947 // be used as the identifier in the declarator for a destructor
4948 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004949 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004950 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004951 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004952 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004953 else if (const TemplateSpecializationType *TST =
4954 DeclaratorType->getAs<TemplateSpecializationType>())
4955 if (TST->isTypeAlias())
4956 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4957 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004958
4959 // C++ [class.dtor]p2:
4960 // A destructor is used to destroy objects of its class type. A
4961 // destructor takes no parameters, and no return type can be
4962 // specified for it (not even void). The address of a destructor
4963 // shall not be taken. A destructor shall not be static. A
4964 // destructor can be invoked for a const, volatile or const
4965 // volatile object. A destructor shall not be declared const,
4966 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004967 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004968 if (!D.isInvalidType())
4969 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4970 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004971 << SourceRange(D.getIdentifierLoc())
4972 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4973
John McCalld931b082010-08-26 03:08:43 +00004974 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004975 }
Chris Lattner65401802009-04-25 08:28:21 +00004976 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004977 // Destructors don't have return types, but the parser will
4978 // happily parse something like:
4979 //
4980 // class X {
4981 // float ~X();
4982 // };
4983 //
4984 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004985 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4986 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4987 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004988 }
Mike Stump1eb44332009-09-09 15:08:12 +00004989
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004990 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004991 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004992 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4994 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004995 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004996 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4997 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004998 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5000 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005001 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005002 }
5003
Douglas Gregorc938c162011-01-26 05:01:58 +00005004 // C++0x [class.dtor]p2:
5005 // A destructor shall not be declared with a ref-qualifier.
5006 if (FTI.hasRefQualifier()) {
5007 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5008 << FTI.RefQualifierIsLValueRef
5009 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5010 D.setInvalidType();
5011 }
5012
Douglas Gregor42a552f2008-11-05 20:51:48 +00005013 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005014 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005015 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5016
5017 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005018 FTI.freeArgs();
5019 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005020 }
5021
Mike Stump1eb44332009-09-09 15:08:12 +00005022 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005023 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005024 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005025 D.setInvalidType();
5026 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005027
5028 // Rebuild the function type "R" without any type qualifiers or
5029 // parameters (in case any of the errors above fired) and with
5030 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005031 // types.
John McCalle23cf432010-12-14 08:05:40 +00005032 if (!D.isInvalidType())
5033 return R;
5034
Douglas Gregord92ec472010-07-01 05:10:53 +00005035 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005036 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5037 EPI.Variadic = false;
5038 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005039 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005040 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005041}
5042
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005043/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5044/// well-formednes of the conversion function declarator @p D with
5045/// type @p R. If there are any errors in the declarator, this routine
5046/// will emit diagnostics and return true. Otherwise, it will return
5047/// false. Either way, the type @p R will be updated to reflect a
5048/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005049void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005050 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005051 // C++ [class.conv.fct]p1:
5052 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005053 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005054 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005055 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005056 if (!D.isInvalidType())
5057 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5058 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5059 << SourceRange(D.getIdentifierLoc());
5060 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005061 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005062 }
John McCalla3f81372010-04-13 00:04:31 +00005063
5064 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5065
Chris Lattner6e475012009-04-25 08:35:12 +00005066 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005067 // Conversion functions don't have return types, but the parser will
5068 // happily parse something like:
5069 //
5070 // class X {
5071 // float operator bool();
5072 // };
5073 //
5074 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005075 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5076 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5077 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005078 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005079 }
5080
John McCalla3f81372010-04-13 00:04:31 +00005081 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5082
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005083 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005084 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005085 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5086
5087 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005088 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005089 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005090 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005091 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005092 D.setInvalidType();
5093 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005094
John McCalla3f81372010-04-13 00:04:31 +00005095 // Diagnose "&operator bool()" and other such nonsense. This
5096 // is actually a gcc extension which we don't support.
5097 if (Proto->getResultType() != ConvType) {
5098 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5099 << Proto->getResultType();
5100 D.setInvalidType();
5101 ConvType = Proto->getResultType();
5102 }
5103
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005104 // C++ [class.conv.fct]p4:
5105 // The conversion-type-id shall not represent a function type nor
5106 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005107 if (ConvType->isArrayType()) {
5108 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5109 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005110 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005111 } else if (ConvType->isFunctionType()) {
5112 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5113 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005114 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005115 }
5116
5117 // Rebuild the function type "R" without any parameters (in case any
5118 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005119 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005120 if (D.isInvalidType())
5121 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005122
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005123 // C++0x explicit conversion operators.
5124 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00005125 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005126 diag::warn_explicit_conversion_functions)
5127 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005128}
5129
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005130/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5131/// the declaration of the given C++ conversion function. This routine
5132/// is responsible for recording the conversion function in the C++
5133/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005134Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005135 assert(Conversion && "Expected to receive a conversion function declaration");
5136
Douglas Gregor9d350972008-12-12 08:25:50 +00005137 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005138
5139 // Make sure we aren't redeclaring the conversion function.
5140 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005141
5142 // C++ [class.conv.fct]p1:
5143 // [...] A conversion function is never used to convert a
5144 // (possibly cv-qualified) object to the (possibly cv-qualified)
5145 // same object type (or a reference to it), to a (possibly
5146 // cv-qualified) base class of that type (or a reference to it),
5147 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005148 // FIXME: Suppress this warning if the conversion function ends up being a
5149 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005150 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005151 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005152 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005153 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005154 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5155 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005156 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005157 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005158 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5159 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005160 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005161 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005162 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005163 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005164 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005165 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005166 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005167 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005168 }
5169
Douglas Gregore80622f2010-09-29 04:25:11 +00005170 if (FunctionTemplateDecl *ConversionTemplate
5171 = Conversion->getDescribedFunctionTemplate())
5172 return ConversionTemplate;
5173
John McCalld226f652010-08-21 09:40:31 +00005174 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005175}
5176
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005177//===----------------------------------------------------------------------===//
5178// Namespace Handling
5179//===----------------------------------------------------------------------===//
5180
John McCallea318642010-08-26 09:15:37 +00005181
5182
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005183/// ActOnStartNamespaceDef - This is called at the start of a namespace
5184/// definition.
John McCalld226f652010-08-21 09:40:31 +00005185Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005186 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005187 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005188 SourceLocation IdentLoc,
5189 IdentifierInfo *II,
5190 SourceLocation LBrace,
5191 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005192 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5193 // For anonymous namespace, take the location of the left brace.
5194 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00005195 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005196 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005197 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005198
5199 Scope *DeclRegionScope = NamespcScope->getParent();
5200
Anders Carlsson2a3503d2010-02-07 01:09:23 +00005201 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5202
John McCall90f14502010-12-10 02:59:44 +00005203 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5204 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005205
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005206 if (II) {
5207 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005208 // The identifier in an original-namespace-definition shall not
5209 // have been previously defined in the declarative region in
5210 // which the original-namespace-definition appears. The
5211 // identifier in an original-namespace-definition is the name of
5212 // the namespace. Subsequently in that declarative region, it is
5213 // treated as an original-namespace-name.
5214 //
5215 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005216 // look through using directives, just look for any ordinary names.
5217
5218 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5219 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5220 Decl::IDNS_Namespace;
5221 NamedDecl *PrevDecl = 0;
5222 for (DeclContext::lookup_result R
5223 = CurContext->getRedeclContext()->lookup(II);
5224 R.first != R.second; ++R.first) {
5225 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5226 PrevDecl = *R.first;
5227 break;
5228 }
5229 }
5230
Douglas Gregor44b43212008-12-11 16:49:14 +00005231 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5232 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005233 if (Namespc->isInline() != OrigNS->isInline()) {
5234 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005235 if (OrigNS->isInline()) {
5236 // The user probably just forgot the 'inline', so suggest that it
5237 // be added back.
5238 Diag(Namespc->getLocation(),
5239 diag::warn_inline_namespace_reopened_noninline)
5240 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5241 } else {
5242 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5243 << Namespc->isInline();
5244 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005245 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005246
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005247 // Recover by ignoring the new namespace's inline status.
5248 Namespc->setInline(OrigNS->isInline());
5249 }
5250
Douglas Gregor44b43212008-12-11 16:49:14 +00005251 // Attach this namespace decl to the chain of extended namespace
5252 // definitions.
5253 OrigNS->setNextNamespace(Namespc);
5254 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005255
Mike Stump1eb44332009-09-09 15:08:12 +00005256 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00005257 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00005258 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00005259 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005260 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005261 } else if (PrevDecl) {
5262 // This is an invalid name redefinition.
5263 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5264 << Namespc->getDeclName();
5265 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5266 Namespc->setInvalidDecl();
5267 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005268 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005269 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005270 // This is the first "real" definition of the namespace "std", so update
5271 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005272 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005273 // We had already defined a dummy namespace "std". Link this new
5274 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005275 StdNS->setNextNamespace(Namespc);
5276 StdNS->setLocation(IdentLoc);
5277 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005278 }
5279
5280 // Make our StdNamespace cache point at the first real definition of the
5281 // "std" namespace.
5282 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005283
5284 // Add this instance of "std" to the set of known namespaces
5285 KnownNamespaces[Namespc] = false;
5286 } else if (!Namespc->isInline()) {
5287 // Since this is an "original" namespace, add it to the known set of
5288 // namespaces if it is not an inline namespace.
5289 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005290 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005291
5292 PushOnScopeChains(Namespc, DeclRegionScope);
5293 } else {
John McCall9aeed322009-10-01 00:25:31 +00005294 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00005295 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00005296
5297 // Link the anonymous namespace into its parent.
5298 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005299 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005300 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5301 PrevDecl = TU->getAnonymousNamespace();
5302 TU->setAnonymousNamespace(Namespc);
5303 } else {
5304 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5305 PrevDecl = ND->getAnonymousNamespace();
5306 ND->setAnonymousNamespace(Namespc);
5307 }
5308
5309 // Link the anonymous namespace with its previous declaration.
5310 if (PrevDecl) {
5311 assert(PrevDecl->isAnonymousNamespace());
5312 assert(!PrevDecl->getNextNamespace());
5313 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5314 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005315
5316 if (Namespc->isInline() != PrevDecl->isInline()) {
5317 // inline-ness must match
5318 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5319 << Namespc->isInline();
5320 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5321 Namespc->setInvalidDecl();
5322 // Recover by ignoring the new namespace's inline status.
5323 Namespc->setInline(PrevDecl->isInline());
5324 }
John McCall5fdd7642009-12-16 02:06:49 +00005325 }
John McCall9aeed322009-10-01 00:25:31 +00005326
Douglas Gregora4181472010-03-24 00:46:35 +00005327 CurContext->addDecl(Namespc);
5328
John McCall9aeed322009-10-01 00:25:31 +00005329 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5330 // behaves as if it were replaced by
5331 // namespace unique { /* empty body */ }
5332 // using namespace unique;
5333 // namespace unique { namespace-body }
5334 // where all occurrences of 'unique' in a translation unit are
5335 // replaced by the same identifier and this identifier differs
5336 // from all other identifiers in the entire program.
5337
5338 // We just create the namespace with an empty name and then add an
5339 // implicit using declaration, just like the standard suggests.
5340 //
5341 // CodeGen enforces the "universally unique" aspect by giving all
5342 // declarations semantically contained within an anonymous
5343 // namespace internal linkage.
5344
John McCall5fdd7642009-12-16 02:06:49 +00005345 if (!PrevDecl) {
5346 UsingDirectiveDecl* UD
5347 = UsingDirectiveDecl::Create(Context, CurContext,
5348 /* 'using' */ LBrace,
5349 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005350 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005351 /* identifier */ SourceLocation(),
5352 Namespc,
5353 /* Ancestor */ CurContext);
5354 UD->setImplicit();
5355 CurContext->addDecl(UD);
5356 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005357 }
5358
5359 // Although we could have an invalid decl (i.e. the namespace name is a
5360 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005361 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5362 // for the namespace has the declarations that showed up in that particular
5363 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005364 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005365 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005366}
5367
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005368/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5369/// is a namespace alias, returns the namespace it points to.
5370static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5371 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5372 return AD->getNamespace();
5373 return dyn_cast_or_null<NamespaceDecl>(D);
5374}
5375
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005376/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5377/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005378void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005379 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5380 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005381 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005382 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005383 if (Namespc->hasAttr<VisibilityAttr>())
5384 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005385}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005386
John McCall384aff82010-08-25 07:42:41 +00005387CXXRecordDecl *Sema::getStdBadAlloc() const {
5388 return cast_or_null<CXXRecordDecl>(
5389 StdBadAlloc.get(Context.getExternalSource()));
5390}
5391
5392NamespaceDecl *Sema::getStdNamespace() const {
5393 return cast_or_null<NamespaceDecl>(
5394 StdNamespace.get(Context.getExternalSource()));
5395}
5396
Douglas Gregor66992202010-06-29 17:53:46 +00005397/// \brief Retrieve the special "std" namespace, which may require us to
5398/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005399NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005400 if (!StdNamespace) {
5401 // The "std" namespace has not yet been defined, so build one implicitly.
5402 StdNamespace = NamespaceDecl::Create(Context,
5403 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005404 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00005405 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005406 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005407 }
5408
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005409 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005410}
5411
Douglas Gregor9172aa62011-03-26 22:25:30 +00005412/// \brief Determine whether a using statement is in a context where it will be
5413/// apply in all contexts.
5414static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5415 switch (CurContext->getDeclKind()) {
5416 case Decl::TranslationUnit:
5417 return true;
5418 case Decl::LinkageSpec:
5419 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5420 default:
5421 return false;
5422 }
5423}
5424
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005425static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5426 CXXScopeSpec &SS,
5427 SourceLocation IdentLoc,
5428 IdentifierInfo *Ident) {
5429 R.clear();
5430 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5431 R.getLookupKind(), Sc, &SS, NULL,
5432 false, S.CTC_NoKeywords, NULL)) {
5433 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5434 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5435 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5436 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5437 if (DeclContext *DC = S.computeDeclContext(SS, false))
5438 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5439 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5440 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5441 else
5442 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5443 << Ident << CorrectedQuotedStr
5444 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5445
5446 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5447 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5448
5449 Ident = Corrected.getCorrectionAsIdentifierInfo();
5450 R.addDecl(Corrected.getCorrectionDecl());
5451 return true;
5452 }
5453 R.setLookupName(Ident);
5454 }
5455 return false;
5456}
5457
John McCalld226f652010-08-21 09:40:31 +00005458Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005459 SourceLocation UsingLoc,
5460 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005461 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005462 SourceLocation IdentLoc,
5463 IdentifierInfo *NamespcName,
5464 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005465 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5466 assert(NamespcName && "Invalid NamespcName.");
5467 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005468
5469 // This can only happen along a recovery path.
5470 while (S->getFlags() & Scope::TemplateParamScope)
5471 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005472 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005473
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005474 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005475 NestedNameSpecifier *Qualifier = 0;
5476 if (SS.isSet())
5477 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5478
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005479 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005480 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5481 LookupParsedName(R, S, &SS);
5482 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005483 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005484
Douglas Gregor66992202010-06-29 17:53:46 +00005485 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005486 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005487 // Allow "using namespace std;" or "using namespace ::std;" even if
5488 // "std" hasn't been defined yet, for GCC compatibility.
5489 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5490 NamespcName->isStr("std")) {
5491 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005492 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005493 R.resolveKind();
5494 }
5495 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005496 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005497 }
5498
John McCallf36e02d2009-10-09 21:13:30 +00005499 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005500 NamedDecl *Named = R.getFoundDecl();
5501 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5502 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005503 // C++ [namespace.udir]p1:
5504 // A using-directive specifies that the names in the nominated
5505 // namespace can be used in the scope in which the
5506 // using-directive appears after the using-directive. During
5507 // unqualified name lookup (3.4.1), the names appear as if they
5508 // were declared in the nearest enclosing namespace which
5509 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005510 // namespace. [Note: in this context, "contains" means "contains
5511 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005512
5513 // Find enclosing context containing both using-directive and
5514 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005515 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005516 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5517 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5518 CommonAncestor = CommonAncestor->getParent();
5519
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005520 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005521 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005522 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005523
Douglas Gregor9172aa62011-03-26 22:25:30 +00005524 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005525 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005526 Diag(IdentLoc, diag::warn_using_directive_in_header);
5527 }
5528
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005529 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005530 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005531 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005532 }
5533
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005534 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005535 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005536}
5537
5538void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5539 // If scope has associated entity, then using directive is at namespace
5540 // or translation unit scope. We add UsingDirectiveDecls, into
5541 // it's lookup structure.
5542 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005543 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005544 else
5545 // Otherwise it is block-sope. using-directives will affect lookup
5546 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005547 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005548}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005549
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005550
John McCalld226f652010-08-21 09:40:31 +00005551Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005552 AccessSpecifier AS,
5553 bool HasUsingKeyword,
5554 SourceLocation UsingLoc,
5555 CXXScopeSpec &SS,
5556 UnqualifiedId &Name,
5557 AttributeList *AttrList,
5558 bool IsTypeName,
5559 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005560 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005561
Douglas Gregor12c118a2009-11-04 16:30:06 +00005562 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005563 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005564 case UnqualifiedId::IK_Identifier:
5565 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005566 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005567 case UnqualifiedId::IK_ConversionFunctionId:
5568 break;
5569
5570 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005571 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005572 // C++0x inherited constructors.
5573 if (getLangOptions().CPlusPlus0x) break;
5574
Douglas Gregor12c118a2009-11-04 16:30:06 +00005575 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5576 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005577 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005578
5579 case UnqualifiedId::IK_DestructorName:
5580 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5581 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005582 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005583
5584 case UnqualifiedId::IK_TemplateId:
5585 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5586 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005587 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005588 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005589
5590 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5591 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005592 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005593 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005594
John McCall60fa3cf2009-12-11 02:10:03 +00005595 // Warn about using declarations.
5596 // TODO: store that the declaration was written without 'using' and
5597 // talk about access decls instead of using decls in the
5598 // diagnostics.
5599 if (!HasUsingKeyword) {
5600 UsingLoc = Name.getSourceRange().getBegin();
5601
5602 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005603 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005604 }
5605
Douglas Gregor56c04582010-12-16 00:46:58 +00005606 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5607 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5608 return 0;
5609
John McCall9488ea12009-11-17 05:59:44 +00005610 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005611 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005612 /* IsInstantiation */ false,
5613 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005614 if (UD)
5615 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005616
John McCalld226f652010-08-21 09:40:31 +00005617 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005618}
5619
Douglas Gregor09acc982010-07-07 23:08:52 +00005620/// \brief Determine whether a using declaration considers the given
5621/// declarations as "equivalent", e.g., if they are redeclarations of
5622/// the same entity or are both typedefs of the same type.
5623static bool
5624IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5625 bool &SuppressRedeclaration) {
5626 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5627 SuppressRedeclaration = false;
5628 return true;
5629 }
5630
Richard Smith162e1c12011-04-15 14:24:37 +00005631 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5632 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005633 SuppressRedeclaration = true;
5634 return Context.hasSameType(TD1->getUnderlyingType(),
5635 TD2->getUnderlyingType());
5636 }
5637
5638 return false;
5639}
5640
5641
John McCall9f54ad42009-12-10 09:41:52 +00005642/// Determines whether to create a using shadow decl for a particular
5643/// decl, given the set of decls existing prior to this using lookup.
5644bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5645 const LookupResult &Previous) {
5646 // Diagnose finding a decl which is not from a base class of the
5647 // current class. We do this now because there are cases where this
5648 // function will silently decide not to build a shadow decl, which
5649 // will pre-empt further diagnostics.
5650 //
5651 // We don't need to do this in C++0x because we do the check once on
5652 // the qualifier.
5653 //
5654 // FIXME: diagnose the following if we care enough:
5655 // struct A { int foo; };
5656 // struct B : A { using A::foo; };
5657 // template <class T> struct C : A {};
5658 // template <class T> struct D : C<T> { using B::foo; } // <---
5659 // This is invalid (during instantiation) in C++03 because B::foo
5660 // resolves to the using decl in B, which is not a base class of D<T>.
5661 // We can't diagnose it immediately because C<T> is an unknown
5662 // specialization. The UsingShadowDecl in D<T> then points directly
5663 // to A::foo, which will look well-formed when we instantiate.
5664 // The right solution is to not collapse the shadow-decl chain.
5665 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5666 DeclContext *OrigDC = Orig->getDeclContext();
5667
5668 // Handle enums and anonymous structs.
5669 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5670 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5671 while (OrigRec->isAnonymousStructOrUnion())
5672 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5673
5674 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5675 if (OrigDC == CurContext) {
5676 Diag(Using->getLocation(),
5677 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005678 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005679 Diag(Orig->getLocation(), diag::note_using_decl_target);
5680 return true;
5681 }
5682
Douglas Gregordc355712011-02-25 00:36:19 +00005683 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005684 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005685 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005686 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005687 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005688 Diag(Orig->getLocation(), diag::note_using_decl_target);
5689 return true;
5690 }
5691 }
5692
5693 if (Previous.empty()) return false;
5694
5695 NamedDecl *Target = Orig;
5696 if (isa<UsingShadowDecl>(Target))
5697 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5698
John McCalld7533ec2009-12-11 02:33:26 +00005699 // If the target happens to be one of the previous declarations, we
5700 // don't have a conflict.
5701 //
5702 // FIXME: but we might be increasing its access, in which case we
5703 // should redeclare it.
5704 NamedDecl *NonTag = 0, *Tag = 0;
5705 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5706 I != E; ++I) {
5707 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005708 bool Result;
5709 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5710 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005711
5712 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5713 }
5714
John McCall9f54ad42009-12-10 09:41:52 +00005715 if (Target->isFunctionOrFunctionTemplate()) {
5716 FunctionDecl *FD;
5717 if (isa<FunctionTemplateDecl>(Target))
5718 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5719 else
5720 FD = cast<FunctionDecl>(Target);
5721
5722 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005723 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005724 case Ovl_Overload:
5725 return false;
5726
5727 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005728 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005729 break;
5730
5731 // We found a decl with the exact signature.
5732 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005733 // If we're in a record, we want to hide the target, so we
5734 // return true (without a diagnostic) to tell the caller not to
5735 // build a shadow decl.
5736 if (CurContext->isRecord())
5737 return true;
5738
5739 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005740 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005741 break;
5742 }
5743
5744 Diag(Target->getLocation(), diag::note_using_decl_target);
5745 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5746 return true;
5747 }
5748
5749 // Target is not a function.
5750
John McCall9f54ad42009-12-10 09:41:52 +00005751 if (isa<TagDecl>(Target)) {
5752 // No conflict between a tag and a non-tag.
5753 if (!Tag) return false;
5754
John McCall41ce66f2009-12-10 19:51:03 +00005755 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005756 Diag(Target->getLocation(), diag::note_using_decl_target);
5757 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5758 return true;
5759 }
5760
5761 // No conflict between a tag and a non-tag.
5762 if (!NonTag) return false;
5763
John McCall41ce66f2009-12-10 19:51:03 +00005764 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005765 Diag(Target->getLocation(), diag::note_using_decl_target);
5766 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5767 return true;
5768}
5769
John McCall9488ea12009-11-17 05:59:44 +00005770/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005771UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005772 UsingDecl *UD,
5773 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005774
5775 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005776 NamedDecl *Target = Orig;
5777 if (isa<UsingShadowDecl>(Target)) {
5778 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5779 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005780 }
5781
5782 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005783 = UsingShadowDecl::Create(Context, CurContext,
5784 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005785 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005786
5787 Shadow->setAccess(UD->getAccess());
5788 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5789 Shadow->setInvalidDecl();
5790
John McCall9488ea12009-11-17 05:59:44 +00005791 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005792 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005793 else
John McCall604e7f12009-12-08 07:46:18 +00005794 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005795
John McCall604e7f12009-12-08 07:46:18 +00005796
John McCall9f54ad42009-12-10 09:41:52 +00005797 return Shadow;
5798}
John McCall604e7f12009-12-08 07:46:18 +00005799
John McCall9f54ad42009-12-10 09:41:52 +00005800/// Hides a using shadow declaration. This is required by the current
5801/// using-decl implementation when a resolvable using declaration in a
5802/// class is followed by a declaration which would hide or override
5803/// one or more of the using decl's targets; for example:
5804///
5805/// struct Base { void foo(int); };
5806/// struct Derived : Base {
5807/// using Base::foo;
5808/// void foo(int);
5809/// };
5810///
5811/// The governing language is C++03 [namespace.udecl]p12:
5812///
5813/// When a using-declaration brings names from a base class into a
5814/// derived class scope, member functions in the derived class
5815/// override and/or hide member functions with the same name and
5816/// parameter types in a base class (rather than conflicting).
5817///
5818/// There are two ways to implement this:
5819/// (1) optimistically create shadow decls when they're not hidden
5820/// by existing declarations, or
5821/// (2) don't create any shadow decls (or at least don't make them
5822/// visible) until we've fully parsed/instantiated the class.
5823/// The problem with (1) is that we might have to retroactively remove
5824/// a shadow decl, which requires several O(n) operations because the
5825/// decl structures are (very reasonably) not designed for removal.
5826/// (2) avoids this but is very fiddly and phase-dependent.
5827void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005828 if (Shadow->getDeclName().getNameKind() ==
5829 DeclarationName::CXXConversionFunctionName)
5830 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5831
John McCall9f54ad42009-12-10 09:41:52 +00005832 // Remove it from the DeclContext...
5833 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005834
John McCall9f54ad42009-12-10 09:41:52 +00005835 // ...and the scope, if applicable...
5836 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005837 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005838 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005839 }
5840
John McCall9f54ad42009-12-10 09:41:52 +00005841 // ...and the using decl.
5842 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5843
5844 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005845 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005846}
5847
John McCall7ba107a2009-11-18 02:36:19 +00005848/// Builds a using declaration.
5849///
5850/// \param IsInstantiation - Whether this call arises from an
5851/// instantiation of an unresolved using declaration. We treat
5852/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005853NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5854 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005855 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005856 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005857 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005858 bool IsInstantiation,
5859 bool IsTypeName,
5860 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005861 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005862 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005863 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005864
Anders Carlsson550b14b2009-08-28 05:49:21 +00005865 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005866
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005867 if (SS.isEmpty()) {
5868 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005869 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005870 }
Mike Stump1eb44332009-09-09 15:08:12 +00005871
John McCall9f54ad42009-12-10 09:41:52 +00005872 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005873 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005874 ForRedeclaration);
5875 Previous.setHideTags(false);
5876 if (S) {
5877 LookupName(Previous, S);
5878
5879 // It is really dumb that we have to do this.
5880 LookupResult::Filter F = Previous.makeFilter();
5881 while (F.hasNext()) {
5882 NamedDecl *D = F.next();
5883 if (!isDeclInScope(D, CurContext, S))
5884 F.erase();
5885 }
5886 F.done();
5887 } else {
5888 assert(IsInstantiation && "no scope in non-instantiation");
5889 assert(CurContext->isRecord() && "scope not record in instantiation");
5890 LookupQualifiedName(Previous, CurContext);
5891 }
5892
John McCall9f54ad42009-12-10 09:41:52 +00005893 // Check for invalid redeclarations.
5894 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5895 return 0;
5896
5897 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005898 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5899 return 0;
5900
John McCallaf8e6ed2009-11-12 03:15:40 +00005901 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005902 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005903 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005904 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005905 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005906 // FIXME: not all declaration name kinds are legal here
5907 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5908 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005909 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005910 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005911 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005912 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5913 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005914 }
John McCalled976492009-12-04 22:46:56 +00005915 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005916 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5917 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005918 }
John McCalled976492009-12-04 22:46:56 +00005919 D->setAccess(AS);
5920 CurContext->addDecl(D);
5921
5922 if (!LookupContext) return D;
5923 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005924
John McCall77bb1aa2010-05-01 00:40:08 +00005925 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005926 UD->setInvalidDecl();
5927 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005928 }
5929
Sebastian Redlf677ea32011-02-05 19:23:19 +00005930 // Constructor inheriting using decls get special treatment.
5931 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005932 if (CheckInheritedConstructorUsingDecl(UD))
5933 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005934 return UD;
5935 }
5936
5937 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005938
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005939 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005940 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005941
John McCall604e7f12009-12-08 07:46:18 +00005942 // Unlike most lookups, we don't always want to hide tag
5943 // declarations: tag names are visible through the using declaration
5944 // even if hidden by ordinary names, *except* in a dependent context
5945 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005946 if (!IsInstantiation)
5947 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005948
John McCalla24dc2e2009-11-17 02:14:36 +00005949 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005950
John McCallf36e02d2009-10-09 21:13:30 +00005951 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005952 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005953 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005954 UD->setInvalidDecl();
5955 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005956 }
5957
John McCalled976492009-12-04 22:46:56 +00005958 if (R.isAmbiguous()) {
5959 UD->setInvalidDecl();
5960 return UD;
5961 }
Mike Stump1eb44332009-09-09 15:08:12 +00005962
John McCall7ba107a2009-11-18 02:36:19 +00005963 if (IsTypeName) {
5964 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005965 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005966 Diag(IdentLoc, diag::err_using_typename_non_type);
5967 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5968 Diag((*I)->getUnderlyingDecl()->getLocation(),
5969 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005970 UD->setInvalidDecl();
5971 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005972 }
5973 } else {
5974 // If we asked for a non-typename and we got a type, error out,
5975 // but only if this is an instantiation of an unresolved using
5976 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005977 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005978 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5979 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005980 UD->setInvalidDecl();
5981 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005982 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005983 }
5984
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005985 // C++0x N2914 [namespace.udecl]p6:
5986 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005987 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005988 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5989 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005990 UD->setInvalidDecl();
5991 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005992 }
Mike Stump1eb44332009-09-09 15:08:12 +00005993
John McCall9f54ad42009-12-10 09:41:52 +00005994 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5995 if (!CheckUsingShadowDecl(UD, *I, Previous))
5996 BuildUsingShadowDecl(S, UD, *I);
5997 }
John McCall9488ea12009-11-17 05:59:44 +00005998
5999 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006000}
6001
Sebastian Redlf677ea32011-02-05 19:23:19 +00006002/// Additional checks for a using declaration referring to a constructor name.
6003bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6004 if (UD->isTypeName()) {
6005 // FIXME: Cannot specify typename when specifying constructor
6006 return true;
6007 }
6008
Douglas Gregordc355712011-02-25 00:36:19 +00006009 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006010 assert(SourceType &&
6011 "Using decl naming constructor doesn't have type in scope spec.");
6012 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6013
6014 // Check whether the named type is a direct base class.
6015 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6016 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6017 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6018 BaseIt != BaseE; ++BaseIt) {
6019 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6020 if (CanonicalSourceType == BaseType)
6021 break;
6022 }
6023
6024 if (BaseIt == BaseE) {
6025 // Did not find SourceType in the bases.
6026 Diag(UD->getUsingLocation(),
6027 diag::err_using_decl_constructor_not_in_direct_base)
6028 << UD->getNameInfo().getSourceRange()
6029 << QualType(SourceType, 0) << TargetClass;
6030 return true;
6031 }
6032
6033 BaseIt->setInheritConstructors();
6034
6035 return false;
6036}
6037
John McCall9f54ad42009-12-10 09:41:52 +00006038/// Checks that the given using declaration is not an invalid
6039/// redeclaration. Note that this is checking only for the using decl
6040/// itself, not for any ill-formedness among the UsingShadowDecls.
6041bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6042 bool isTypeName,
6043 const CXXScopeSpec &SS,
6044 SourceLocation NameLoc,
6045 const LookupResult &Prev) {
6046 // C++03 [namespace.udecl]p8:
6047 // C++0x [namespace.udecl]p10:
6048 // A using-declaration is a declaration and can therefore be used
6049 // repeatedly where (and only where) multiple declarations are
6050 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006051 //
John McCall8a726212010-11-29 18:01:58 +00006052 // That's in non-member contexts.
6053 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006054 return false;
6055
6056 NestedNameSpecifier *Qual
6057 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6058
6059 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6060 NamedDecl *D = *I;
6061
6062 bool DTypename;
6063 NestedNameSpecifier *DQual;
6064 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6065 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006066 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006067 } else if (UnresolvedUsingValueDecl *UD
6068 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6069 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006070 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006071 } else if (UnresolvedUsingTypenameDecl *UD
6072 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6073 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006074 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006075 } else continue;
6076
6077 // using decls differ if one says 'typename' and the other doesn't.
6078 // FIXME: non-dependent using decls?
6079 if (isTypeName != DTypename) continue;
6080
6081 // using decls differ if they name different scopes (but note that
6082 // template instantiation can cause this check to trigger when it
6083 // didn't before instantiation).
6084 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6085 Context.getCanonicalNestedNameSpecifier(DQual))
6086 continue;
6087
6088 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006089 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006090 return true;
6091 }
6092
6093 return false;
6094}
6095
John McCall604e7f12009-12-08 07:46:18 +00006096
John McCalled976492009-12-04 22:46:56 +00006097/// Checks that the given nested-name qualifier used in a using decl
6098/// in the current context is appropriately related to the current
6099/// scope. If an error is found, diagnoses it and returns true.
6100bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6101 const CXXScopeSpec &SS,
6102 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006103 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006104
John McCall604e7f12009-12-08 07:46:18 +00006105 if (!CurContext->isRecord()) {
6106 // C++03 [namespace.udecl]p3:
6107 // C++0x [namespace.udecl]p8:
6108 // A using-declaration for a class member shall be a member-declaration.
6109
6110 // If we weren't able to compute a valid scope, it must be a
6111 // dependent class scope.
6112 if (!NamedContext || NamedContext->isRecord()) {
6113 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6114 << SS.getRange();
6115 return true;
6116 }
6117
6118 // Otherwise, everything is known to be fine.
6119 return false;
6120 }
6121
6122 // The current scope is a record.
6123
6124 // If the named context is dependent, we can't decide much.
6125 if (!NamedContext) {
6126 // FIXME: in C++0x, we can diagnose if we can prove that the
6127 // nested-name-specifier does not refer to a base class, which is
6128 // still possible in some cases.
6129
6130 // Otherwise we have to conservatively report that things might be
6131 // okay.
6132 return false;
6133 }
6134
6135 if (!NamedContext->isRecord()) {
6136 // Ideally this would point at the last name in the specifier,
6137 // but we don't have that level of source info.
6138 Diag(SS.getRange().getBegin(),
6139 diag::err_using_decl_nested_name_specifier_is_not_class)
6140 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6141 return true;
6142 }
6143
Douglas Gregor6fb07292010-12-21 07:41:49 +00006144 if (!NamedContext->isDependentContext() &&
6145 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6146 return true;
6147
John McCall604e7f12009-12-08 07:46:18 +00006148 if (getLangOptions().CPlusPlus0x) {
6149 // C++0x [namespace.udecl]p3:
6150 // In a using-declaration used as a member-declaration, the
6151 // nested-name-specifier shall name a base class of the class
6152 // being defined.
6153
6154 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6155 cast<CXXRecordDecl>(NamedContext))) {
6156 if (CurContext == NamedContext) {
6157 Diag(NameLoc,
6158 diag::err_using_decl_nested_name_specifier_is_current_class)
6159 << SS.getRange();
6160 return true;
6161 }
6162
6163 Diag(SS.getRange().getBegin(),
6164 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6165 << (NestedNameSpecifier*) SS.getScopeRep()
6166 << cast<CXXRecordDecl>(CurContext)
6167 << SS.getRange();
6168 return true;
6169 }
6170
6171 return false;
6172 }
6173
6174 // C++03 [namespace.udecl]p4:
6175 // A using-declaration used as a member-declaration shall refer
6176 // to a member of a base class of the class being defined [etc.].
6177
6178 // Salient point: SS doesn't have to name a base class as long as
6179 // lookup only finds members from base classes. Therefore we can
6180 // diagnose here only if we can prove that that can't happen,
6181 // i.e. if the class hierarchies provably don't intersect.
6182
6183 // TODO: it would be nice if "definitely valid" results were cached
6184 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6185 // need to be repeated.
6186
6187 struct UserData {
6188 llvm::DenseSet<const CXXRecordDecl*> Bases;
6189
6190 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6191 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6192 Data->Bases.insert(Base);
6193 return true;
6194 }
6195
6196 bool hasDependentBases(const CXXRecordDecl *Class) {
6197 return !Class->forallBases(collect, this);
6198 }
6199
6200 /// Returns true if the base is dependent or is one of the
6201 /// accumulated base classes.
6202 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6203 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6204 return !Data->Bases.count(Base);
6205 }
6206
6207 bool mightShareBases(const CXXRecordDecl *Class) {
6208 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6209 }
6210 };
6211
6212 UserData Data;
6213
6214 // Returns false if we find a dependent base.
6215 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6216 return false;
6217
6218 // Returns false if the class has a dependent base or if it or one
6219 // of its bases is present in the base set of the current context.
6220 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6221 return false;
6222
6223 Diag(SS.getRange().getBegin(),
6224 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6225 << (NestedNameSpecifier*) SS.getScopeRep()
6226 << cast<CXXRecordDecl>(CurContext)
6227 << SS.getRange();
6228
6229 return true;
John McCalled976492009-12-04 22:46:56 +00006230}
6231
Richard Smith162e1c12011-04-15 14:24:37 +00006232Decl *Sema::ActOnAliasDeclaration(Scope *S,
6233 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006234 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006235 SourceLocation UsingLoc,
6236 UnqualifiedId &Name,
6237 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006238 // Skip up to the relevant declaration scope.
6239 while (S->getFlags() & Scope::TemplateParamScope)
6240 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006241 assert((S->getFlags() & Scope::DeclScope) &&
6242 "got alias-declaration outside of declaration scope");
6243
6244 if (Type.isInvalid())
6245 return 0;
6246
6247 bool Invalid = false;
6248 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6249 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006250 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006251
6252 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6253 return 0;
6254
6255 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006256 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006257 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006258 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6259 TInfo->getTypeLoc().getBeginLoc());
6260 }
Richard Smith162e1c12011-04-15 14:24:37 +00006261
6262 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6263 LookupName(Previous, S);
6264
6265 // Warn about shadowing the name of a template parameter.
6266 if (Previous.isSingleResult() &&
6267 Previous.getFoundDecl()->isTemplateParameter()) {
6268 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6269 Previous.getFoundDecl()))
6270 Invalid = true;
6271 Previous.clear();
6272 }
6273
6274 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6275 "name in alias declaration must be an identifier");
6276 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6277 Name.StartLocation,
6278 Name.Identifier, TInfo);
6279
6280 NewTD->setAccess(AS);
6281
6282 if (Invalid)
6283 NewTD->setInvalidDecl();
6284
Richard Smith3e4c6c42011-05-05 21:57:07 +00006285 CheckTypedefForVariablyModifiedType(S, NewTD);
6286 Invalid |= NewTD->isInvalidDecl();
6287
Richard Smith162e1c12011-04-15 14:24:37 +00006288 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006289
6290 NamedDecl *NewND;
6291 if (TemplateParamLists.size()) {
6292 TypeAliasTemplateDecl *OldDecl = 0;
6293 TemplateParameterList *OldTemplateParams = 0;
6294
6295 if (TemplateParamLists.size() != 1) {
6296 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6297 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6298 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6299 }
6300 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6301
6302 // Only consider previous declarations in the same scope.
6303 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6304 /*ExplicitInstantiationOrSpecialization*/false);
6305 if (!Previous.empty()) {
6306 Redeclaration = true;
6307
6308 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6309 if (!OldDecl && !Invalid) {
6310 Diag(UsingLoc, diag::err_redefinition_different_kind)
6311 << Name.Identifier;
6312
6313 NamedDecl *OldD = Previous.getRepresentativeDecl();
6314 if (OldD->getLocation().isValid())
6315 Diag(OldD->getLocation(), diag::note_previous_definition);
6316
6317 Invalid = true;
6318 }
6319
6320 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6321 if (TemplateParameterListsAreEqual(TemplateParams,
6322 OldDecl->getTemplateParameters(),
6323 /*Complain=*/true,
6324 TPL_TemplateMatch))
6325 OldTemplateParams = OldDecl->getTemplateParameters();
6326 else
6327 Invalid = true;
6328
6329 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6330 if (!Invalid &&
6331 !Context.hasSameType(OldTD->getUnderlyingType(),
6332 NewTD->getUnderlyingType())) {
6333 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6334 // but we can't reasonably accept it.
6335 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6336 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6337 if (OldTD->getLocation().isValid())
6338 Diag(OldTD->getLocation(), diag::note_previous_definition);
6339 Invalid = true;
6340 }
6341 }
6342 }
6343
6344 // Merge any previous default template arguments into our parameters,
6345 // and check the parameter list.
6346 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6347 TPC_TypeAliasTemplate))
6348 return 0;
6349
6350 TypeAliasTemplateDecl *NewDecl =
6351 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6352 Name.Identifier, TemplateParams,
6353 NewTD);
6354
6355 NewDecl->setAccess(AS);
6356
6357 if (Invalid)
6358 NewDecl->setInvalidDecl();
6359 else if (OldDecl)
6360 NewDecl->setPreviousDeclaration(OldDecl);
6361
6362 NewND = NewDecl;
6363 } else {
6364 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6365 NewND = NewTD;
6366 }
Richard Smith162e1c12011-04-15 14:24:37 +00006367
6368 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006369 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006370
Richard Smith3e4c6c42011-05-05 21:57:07 +00006371 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006372}
6373
John McCalld226f652010-08-21 09:40:31 +00006374Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006375 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006376 SourceLocation AliasLoc,
6377 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006378 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006379 SourceLocation IdentLoc,
6380 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006381
Anders Carlsson81c85c42009-03-28 23:53:49 +00006382 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006383 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6384 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006385
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006386 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006387 NamedDecl *PrevDecl
6388 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6389 ForRedeclaration);
6390 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6391 PrevDecl = 0;
6392
6393 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006394 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006395 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006396 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006397 // FIXME: At some point, we'll want to create the (redundant)
6398 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006399 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006400 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006401 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006402 }
Mike Stump1eb44332009-09-09 15:08:12 +00006403
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006404 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6405 diag::err_redefinition_different_kind;
6406 Diag(AliasLoc, DiagID) << Alias;
6407 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006408 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006409 }
6410
John McCalla24dc2e2009-11-17 02:14:36 +00006411 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006412 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006413
John McCallf36e02d2009-10-09 21:13:30 +00006414 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006415 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006416 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006417 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006418 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006419 }
Mike Stump1eb44332009-09-09 15:08:12 +00006420
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006421 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006422 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006423 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006424 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006425
John McCall3dbd3d52010-02-16 06:53:13 +00006426 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006427 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006428}
6429
Douglas Gregor39957dc2010-05-01 15:04:51 +00006430namespace {
6431 /// \brief Scoped object used to handle the state changes required in Sema
6432 /// to implicitly define the body of a C++ member function;
6433 class ImplicitlyDefinedFunctionScope {
6434 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006435 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006436
6437 public:
6438 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006439 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006440 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006441 S.PushFunctionScope();
6442 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6443 }
6444
6445 ~ImplicitlyDefinedFunctionScope() {
6446 S.PopExpressionEvaluationContext();
6447 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006448 }
6449 };
6450}
6451
Sean Hunt001cad92011-05-10 00:49:42 +00006452Sema::ImplicitExceptionSpecification
6453Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006454 // C++ [except.spec]p14:
6455 // An implicitly declared special member function (Clause 12) shall have an
6456 // exception-specification. [...]
6457 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006458 if (ClassDecl->isInvalidDecl())
6459 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006460
Sebastian Redl60618fa2011-03-12 11:50:43 +00006461 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006462 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6463 BEnd = ClassDecl->bases_end();
6464 B != BEnd; ++B) {
6465 if (B->isVirtual()) // Handled below.
6466 continue;
6467
Douglas Gregor18274032010-07-03 00:47:00 +00006468 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6469 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006470 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6471 // If this is a deleted function, add it anyway. This might be conformant
6472 // with the standard. This might not. I'm not sure. It might not matter.
6473 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006474 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006475 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006476 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006477
6478 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006479 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6480 BEnd = ClassDecl->vbases_end();
6481 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006482 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6483 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006484 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6485 // If this is a deleted function, add it anyway. This might be conformant
6486 // with the standard. This might not. I'm not sure. It might not matter.
6487 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006488 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006489 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006490 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006491
6492 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006493 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6494 FEnd = ClassDecl->field_end();
6495 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006496 if (F->hasInClassInitializer()) {
6497 if (Expr *E = F->getInClassInitializer())
6498 ExceptSpec.CalledExpr(E);
6499 else if (!F->isInvalidDecl())
6500 ExceptSpec.SetDelayed();
6501 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006502 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006503 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6504 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6505 // If this is a deleted function, add it anyway. This might be conformant
6506 // with the standard. This might not. I'm not sure. It might not matter.
6507 // In particular, the problem is that this function never gets called. It
6508 // might just be ill-formed because this function attempts to refer to
6509 // a deleted function here.
6510 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006511 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006512 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006513 }
John McCalle23cf432010-12-14 08:05:40 +00006514
Sean Hunt001cad92011-05-10 00:49:42 +00006515 return ExceptSpec;
6516}
6517
6518CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6519 CXXRecordDecl *ClassDecl) {
6520 // C++ [class.ctor]p5:
6521 // A default constructor for a class X is a constructor of class X
6522 // that can be called without an argument. If there is no
6523 // user-declared constructor for class X, a default constructor is
6524 // implicitly declared. An implicitly-declared default constructor
6525 // is an inline public member of its class.
6526 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6527 "Should not build implicit default constructor!");
6528
6529 ImplicitExceptionSpecification Spec =
6530 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6531 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006532
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006533 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006534 CanQualType ClassType
6535 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006536 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006537 DeclarationName Name
6538 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006539 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006540 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006541 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006542 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006543 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006544 /*TInfo=*/0,
6545 /*isExplicit=*/false,
6546 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006547 /*isImplicitlyDeclared=*/true,
6548 // FIXME: apply the rules for definitions here
6549 /*isConstexpr=*/false);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006550 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006551 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006552 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006553 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006554
6555 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006556 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6557
Douglas Gregor23c94db2010-07-02 17:43:08 +00006558 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006559 PushOnScopeChains(DefaultCon, S, false);
6560 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006561
6562 if (ShouldDeleteDefaultConstructor(DefaultCon))
6563 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006564
Douglas Gregor32df23e2010-07-01 22:02:46 +00006565 return DefaultCon;
6566}
6567
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006568void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6569 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006570 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006571 !Constructor->doesThisDeclarationHaveABody() &&
6572 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006573 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006574
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006575 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006576 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006577
Douglas Gregor39957dc2010-05-01 15:04:51 +00006578 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006579 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006580 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006581 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006582 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006583 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006584 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006585 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006586 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006587
6588 SourceLocation Loc = Constructor->getLocation();
6589 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6590
6591 Constructor->setUsed();
6592 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006593
6594 if (ASTMutationListener *L = getASTMutationListener()) {
6595 L->CompletedImplicitDefinition(Constructor);
6596 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006597}
6598
Richard Smith7a614d82011-06-11 17:19:42 +00006599/// Get any existing defaulted default constructor for the given class. Do not
6600/// implicitly define one if it does not exist.
6601static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6602 CXXRecordDecl *D) {
6603 ASTContext &Context = Self.Context;
6604 QualType ClassType = Context.getTypeDeclType(D);
6605 DeclarationName ConstructorName
6606 = Context.DeclarationNames.getCXXConstructorName(
6607 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6608
6609 DeclContext::lookup_const_iterator Con, ConEnd;
6610 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6611 Con != ConEnd; ++Con) {
6612 // A function template cannot be defaulted.
6613 if (isa<FunctionTemplateDecl>(*Con))
6614 continue;
6615
6616 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6617 if (Constructor->isDefaultConstructor())
6618 return Constructor->isDefaulted() ? Constructor : 0;
6619 }
6620 return 0;
6621}
6622
6623void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6624 if (!D) return;
6625 AdjustDeclIfTemplate(D);
6626
6627 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6628 CXXConstructorDecl *CtorDecl
6629 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6630
6631 if (!CtorDecl) return;
6632
6633 // Compute the exception specification for the default constructor.
6634 const FunctionProtoType *CtorTy =
6635 CtorDecl->getType()->castAs<FunctionProtoType>();
6636 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6637 ImplicitExceptionSpecification Spec =
6638 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6639 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6640 assert(EPI.ExceptionSpecType != EST_Delayed);
6641
6642 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6643 }
6644
6645 // If the default constructor is explicitly defaulted, checking the exception
6646 // specification is deferred until now.
6647 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6648 !ClassDecl->isDependentType())
6649 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6650}
6651
Sebastian Redlf677ea32011-02-05 19:23:19 +00006652void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6653 // We start with an initial pass over the base classes to collect those that
6654 // inherit constructors from. If there are none, we can forgo all further
6655 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006656 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006657 BasesVector BasesToInheritFrom;
6658 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6659 BaseE = ClassDecl->bases_end();
6660 BaseIt != BaseE; ++BaseIt) {
6661 if (BaseIt->getInheritConstructors()) {
6662 QualType Base = BaseIt->getType();
6663 if (Base->isDependentType()) {
6664 // If we inherit constructors from anything that is dependent, just
6665 // abort processing altogether. We'll get another chance for the
6666 // instantiations.
6667 return;
6668 }
6669 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6670 }
6671 }
6672 if (BasesToInheritFrom.empty())
6673 return;
6674
6675 // Now collect the constructors that we already have in the current class.
6676 // Those take precedence over inherited constructors.
6677 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6678 // unless there is a user-declared constructor with the same signature in
6679 // the class where the using-declaration appears.
6680 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6681 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6682 CtorE = ClassDecl->ctor_end();
6683 CtorIt != CtorE; ++CtorIt) {
6684 ExistingConstructors.insert(
6685 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6686 }
6687
6688 Scope *S = getScopeForContext(ClassDecl);
6689 DeclarationName CreatedCtorName =
6690 Context.DeclarationNames.getCXXConstructorName(
6691 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6692
6693 // Now comes the true work.
6694 // First, we keep a map from constructor types to the base that introduced
6695 // them. Needed for finding conflicting constructors. We also keep the
6696 // actually inserted declarations in there, for pretty diagnostics.
6697 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6698 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6699 ConstructorToSourceMap InheritedConstructors;
6700 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6701 BaseE = BasesToInheritFrom.end();
6702 BaseIt != BaseE; ++BaseIt) {
6703 const RecordType *Base = *BaseIt;
6704 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6705 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6706 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6707 CtorE = BaseDecl->ctor_end();
6708 CtorIt != CtorE; ++CtorIt) {
6709 // Find the using declaration for inheriting this base's constructors.
6710 DeclarationName Name =
6711 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6712 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6713 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6714 SourceLocation UsingLoc = UD ? UD->getLocation() :
6715 ClassDecl->getLocation();
6716
6717 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6718 // from the class X named in the using-declaration consists of actual
6719 // constructors and notional constructors that result from the
6720 // transformation of defaulted parameters as follows:
6721 // - all non-template default constructors of X, and
6722 // - for each non-template constructor of X that has at least one
6723 // parameter with a default argument, the set of constructors that
6724 // results from omitting any ellipsis parameter specification and
6725 // successively omitting parameters with a default argument from the
6726 // end of the parameter-type-list.
6727 CXXConstructorDecl *BaseCtor = *CtorIt;
6728 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6729 const FunctionProtoType *BaseCtorType =
6730 BaseCtor->getType()->getAs<FunctionProtoType>();
6731
6732 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6733 maxParams = BaseCtor->getNumParams();
6734 params <= maxParams; ++params) {
6735 // Skip default constructors. They're never inherited.
6736 if (params == 0)
6737 continue;
6738 // Skip copy and move constructors for the same reason.
6739 if (CanBeCopyOrMove && params == 1)
6740 continue;
6741
6742 // Build up a function type for this particular constructor.
6743 // FIXME: The working paper does not consider that the exception spec
6744 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006745 // source. This code doesn't yet, either. When it does, this code will
6746 // need to be delayed until after exception specifications and in-class
6747 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006748 const Type *NewCtorType;
6749 if (params == maxParams)
6750 NewCtorType = BaseCtorType;
6751 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006752 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006753 for (unsigned i = 0; i < params; ++i) {
6754 Args.push_back(BaseCtorType->getArgType(i));
6755 }
6756 FunctionProtoType::ExtProtoInfo ExtInfo =
6757 BaseCtorType->getExtProtoInfo();
6758 ExtInfo.Variadic = false;
6759 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6760 Args.data(), params, ExtInfo)
6761 .getTypePtr();
6762 }
6763 const Type *CanonicalNewCtorType =
6764 Context.getCanonicalType(NewCtorType);
6765
6766 // Now that we have the type, first check if the class already has a
6767 // constructor with this signature.
6768 if (ExistingConstructors.count(CanonicalNewCtorType))
6769 continue;
6770
6771 // Then we check if we have already declared an inherited constructor
6772 // with this signature.
6773 std::pair<ConstructorToSourceMap::iterator, bool> result =
6774 InheritedConstructors.insert(std::make_pair(
6775 CanonicalNewCtorType,
6776 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6777 if (!result.second) {
6778 // Already in the map. If it came from a different class, that's an
6779 // error. Not if it's from the same.
6780 CanQualType PreviousBase = result.first->second.first;
6781 if (CanonicalBase != PreviousBase) {
6782 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6783 const CXXConstructorDecl *PrevBaseCtor =
6784 PrevCtor->getInheritedConstructor();
6785 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6786
6787 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6788 Diag(BaseCtor->getLocation(),
6789 diag::note_using_decl_constructor_conflict_current_ctor);
6790 Diag(PrevBaseCtor->getLocation(),
6791 diag::note_using_decl_constructor_conflict_previous_ctor);
6792 Diag(PrevCtor->getLocation(),
6793 diag::note_using_decl_constructor_conflict_previous_using);
6794 }
6795 continue;
6796 }
6797
6798 // OK, we're there, now add the constructor.
6799 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006800 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006801 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6802 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006803 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6804 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006805 /*ImplicitlyDeclared=*/true,
6806 // FIXME: Due to a defect in the standard, we treat inherited
6807 // constructors as constexpr even if that makes them ill-formed.
6808 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006809 NewCtor->setAccess(BaseCtor->getAccess());
6810
6811 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006812 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006813 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006814 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6815 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006816 /*IdentifierInfo=*/0,
6817 BaseCtorType->getArgType(i),
6818 /*TInfo=*/0, SC_None,
6819 SC_None, /*DefaultArg=*/0));
6820 }
6821 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6822 NewCtor->setInheritedConstructor(BaseCtor);
6823
6824 PushOnScopeChains(NewCtor, S, false);
6825 ClassDecl->addDecl(NewCtor);
6826 result.first->second.second = NewCtor;
6827 }
6828 }
6829 }
6830}
6831
Sean Huntcb45a0f2011-05-12 22:46:25 +00006832Sema::ImplicitExceptionSpecification
6833Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006834 // C++ [except.spec]p14:
6835 // An implicitly declared special member function (Clause 12) shall have
6836 // an exception-specification.
6837 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006838 if (ClassDecl->isInvalidDecl())
6839 return ExceptSpec;
6840
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006841 // Direct base-class destructors.
6842 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6843 BEnd = ClassDecl->bases_end();
6844 B != BEnd; ++B) {
6845 if (B->isVirtual()) // Handled below.
6846 continue;
6847
6848 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6849 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006850 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006851 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006852
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006853 // Virtual base-class destructors.
6854 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6855 BEnd = ClassDecl->vbases_end();
6856 B != BEnd; ++B) {
6857 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6858 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006859 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006860 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006861
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006862 // Field destructors.
6863 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6864 FEnd = ClassDecl->field_end();
6865 F != FEnd; ++F) {
6866 if (const RecordType *RecordTy
6867 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6868 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006869 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006870 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006871
Sean Huntcb45a0f2011-05-12 22:46:25 +00006872 return ExceptSpec;
6873}
6874
6875CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6876 // C++ [class.dtor]p2:
6877 // If a class has no user-declared destructor, a destructor is
6878 // declared implicitly. An implicitly-declared destructor is an
6879 // inline public member of its class.
6880
6881 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006882 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006883 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6884
Douglas Gregor4923aa22010-07-02 20:37:36 +00006885 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006886 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006887
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006888 CanQualType ClassType
6889 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006890 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006891 DeclarationName Name
6892 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006893 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006894 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006895 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6896 /*isInline=*/true,
6897 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006898 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006899 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006900 Destructor->setImplicit();
6901 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006902
6903 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006904 ++ASTContext::NumImplicitDestructorsDeclared;
6905
6906 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006907 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006908 PushOnScopeChains(Destructor, S, false);
6909 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006910
6911 // This could be uniqued if it ever proves significant.
6912 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006913
6914 if (ShouldDeleteDestructor(Destructor))
6915 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006916
6917 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006918
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006919 return Destructor;
6920}
6921
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006922void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006923 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006924 assert((Destructor->isDefaulted() &&
6925 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006926 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006927 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006928 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006929
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006930 if (Destructor->isInvalidDecl())
6931 return;
6932
Douglas Gregor39957dc2010-05-01 15:04:51 +00006933 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006934
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006935 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006936 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6937 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006938
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006939 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006940 Diag(CurrentLocation, diag::note_member_synthesized_at)
6941 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6942
6943 Destructor->setInvalidDecl();
6944 return;
6945 }
6946
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006947 SourceLocation Loc = Destructor->getLocation();
6948 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6949
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006950 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006951 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006952
6953 if (ASTMutationListener *L = getASTMutationListener()) {
6954 L->CompletedImplicitDefinition(Destructor);
6955 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006956}
6957
Sebastian Redl0ee33912011-05-19 05:13:44 +00006958void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6959 CXXDestructorDecl *destructor) {
6960 // C++11 [class.dtor]p3:
6961 // A declaration of a destructor that does not have an exception-
6962 // specification is implicitly considered to have the same exception-
6963 // specification as an implicit declaration.
6964 const FunctionProtoType *dtorType = destructor->getType()->
6965 getAs<FunctionProtoType>();
6966 if (dtorType->hasExceptionSpec())
6967 return;
6968
6969 ImplicitExceptionSpecification exceptSpec =
6970 ComputeDefaultedDtorExceptionSpec(classDecl);
6971
6972 // Replace the destructor's type.
6973 FunctionProtoType::ExtProtoInfo epi;
6974 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6975 epi.NumExceptions = exceptSpec.size();
6976 epi.Exceptions = exceptSpec.data();
6977 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6978
6979 destructor->setType(ty);
6980
6981 // FIXME: If the destructor has a body that could throw, and the newly created
6982 // spec doesn't allow exceptions, we should emit a warning, because this
6983 // change in behavior can break conforming C++03 programs at runtime.
6984 // However, we don't have a body yet, so it needs to be done somewhere else.
6985}
6986
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006987/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00006988/// \c To.
6989///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006990/// This routine is used to copy/move the members of a class with an
6991/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00006992/// copied are arrays, this routine builds for loops to copy them.
6993///
6994/// \param S The Sema object used for type-checking.
6995///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006996/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006997///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006998/// \param T The type of the expressions being copied/moved. Both expressions
6999/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007000///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007001/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007002///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007003/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007004///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007005/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007006/// Otherwise, it's a non-static member subobject.
7007///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007008/// \param Copying Whether we're copying or moving.
7009///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007010/// \param Depth Internal parameter recording the depth of the recursion.
7011///
7012/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007013static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007014BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007015 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007016 bool CopyingBaseSubobject, bool Copying,
7017 unsigned Depth = 0) {
7018 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007019 // Each subobject is assigned in the manner appropriate to its type:
7020 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007021 // - if the subobject is of class type, as if by a call to operator= with
7022 // the subobject as the object expression and the corresponding
7023 // subobject of x as a single function argument (as if by explicit
7024 // qualification; that is, ignoring any possible virtual overriding
7025 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007026 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7027 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7028
7029 // Look for operator=.
7030 DeclarationName Name
7031 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7032 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7033 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7034
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007035 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007036 LookupResult::Filter F = OpLookup.makeFilter();
7037 while (F.hasNext()) {
7038 NamedDecl *D = F.next();
7039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007040 if (Copying ? Method->isCopyAssignmentOperator() :
7041 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007042 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007043
Douglas Gregor06a9f362010-05-01 20:49:11 +00007044 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007045 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007046 F.done();
7047
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007048 // Suppress the protected check (C++ [class.protected]) for each of the
7049 // assignment operators we found. This strange dance is required when
7050 // we're assigning via a base classes's copy-assignment operator. To
7051 // ensure that we're getting the right base class subobject (without
7052 // ambiguities), we need to cast "this" to that subobject type; to
7053 // ensure that we don't go through the virtual call mechanism, we need
7054 // to qualify the operator= name with the base class (see below). However,
7055 // this means that if the base class has a protected copy assignment
7056 // operator, the protected member access check will fail. So, we
7057 // rewrite "protected" access to "public" access in this case, since we
7058 // know by construction that we're calling from a derived class.
7059 if (CopyingBaseSubobject) {
7060 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7061 L != LEnd; ++L) {
7062 if (L.getAccess() == AS_protected)
7063 L.setAccess(AS_public);
7064 }
7065 }
7066
Douglas Gregor06a9f362010-05-01 20:49:11 +00007067 // Create the nested-name-specifier that will be used to qualify the
7068 // reference to operator=; this is required to suppress the virtual
7069 // call mechanism.
7070 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007071 SS.MakeTrivial(S.Context,
7072 NestedNameSpecifier::Create(S.Context, 0, false,
7073 T.getTypePtr()),
7074 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007075
7076 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007077 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007078 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007079 /*FirstQualifierInScope=*/0, OpLookup,
7080 /*TemplateArgs=*/0,
7081 /*SuppressQualifierCheck=*/true);
7082 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007083 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007084
7085 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007086
John McCall60d7b3a2010-08-24 06:29:42 +00007087 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007088 OpEqualRef.takeAs<Expr>(),
7089 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007090 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007091 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007092
7093 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007094 }
John McCallb0207482010-03-16 06:11:48 +00007095
Douglas Gregor06a9f362010-05-01 20:49:11 +00007096 // - if the subobject is of scalar type, the built-in assignment
7097 // operator is used.
7098 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7099 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007100 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007101 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007102 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007103
7104 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007105 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007106
7107 // - if the subobject is an array, each element is assigned, in the
7108 // manner appropriate to the element type;
7109
7110 // Construct a loop over the array bounds, e.g.,
7111 //
7112 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7113 //
7114 // that will copy each of the array elements.
7115 QualType SizeType = S.Context.getSizeType();
7116
7117 // Create the iteration variable.
7118 IdentifierInfo *IterationVarName = 0;
7119 {
7120 llvm::SmallString<8> Str;
7121 llvm::raw_svector_ostream OS(Str);
7122 OS << "__i" << Depth;
7123 IterationVarName = &S.Context.Idents.get(OS.str());
7124 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007125 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007126 IterationVarName, SizeType,
7127 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007128 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007129
7130 // Initialize the iteration variable to zero.
7131 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007132 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007133
7134 // Create a reference to the iteration variable; we'll use this several
7135 // times throughout.
7136 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007137 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007138 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7139
7140 // Create the DeclStmt that holds the iteration variable.
7141 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7142
7143 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007144 llvm::APInt Upper
7145 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007146 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007147 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007148 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7149 BO_NE, S.Context.BoolTy,
7150 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007151
7152 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007153 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007154 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7155 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007156
7157 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007158 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7159 IterationVarRef, Loc));
7160 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7161 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007162 if (!Copying) // Cast to rvalue
7163 From = CastForMoving(S, From);
7164
7165 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007166 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7167 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007168 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007169 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007170 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007171
7172 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007173 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007174 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007175 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007176 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007177}
7178
Sean Hunt30de05c2011-05-14 05:23:20 +00007179std::pair<Sema::ImplicitExceptionSpecification, bool>
7180Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7181 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007182 if (ClassDecl->isInvalidDecl())
7183 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7184
Douglas Gregord3c35902010-07-01 16:36:15 +00007185 // C++ [class.copy]p10:
7186 // If the class definition does not explicitly declare a copy
7187 // assignment operator, one is declared implicitly.
7188 // The implicitly-defined copy assignment operator for a class X
7189 // will have the form
7190 //
7191 // X& X::operator=(const X&)
7192 //
7193 // if
7194 bool HasConstCopyAssignment = true;
7195
7196 // -- each direct base class B of X has a copy assignment operator
7197 // whose parameter is of type const B&, const volatile B& or B,
7198 // and
7199 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7200 BaseEnd = ClassDecl->bases_end();
7201 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007202 // We'll handle this below
7203 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7204 continue;
7205
Douglas Gregord3c35902010-07-01 16:36:15 +00007206 assert(!Base->getType()->isDependentType() &&
7207 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007208 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7209 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7210 &HasConstCopyAssignment);
7211 }
7212
7213 // In C++0x, the above citation has "or virtual added"
7214 if (LangOpts.CPlusPlus0x) {
7215 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7216 BaseEnd = ClassDecl->vbases_end();
7217 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7218 assert(!Base->getType()->isDependentType() &&
7219 "Cannot generate implicit members for class with dependent bases.");
7220 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7221 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7222 &HasConstCopyAssignment);
7223 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007224 }
7225
7226 // -- for all the nonstatic data members of X that are of a class
7227 // type M (or array thereof), each such class type has a copy
7228 // assignment operator whose parameter is of type const M&,
7229 // const volatile M& or M.
7230 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7231 FieldEnd = ClassDecl->field_end();
7232 HasConstCopyAssignment && Field != FieldEnd;
7233 ++Field) {
7234 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007235 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7236 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7237 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007238 }
7239 }
7240
7241 // Otherwise, the implicitly declared copy assignment operator will
7242 // have the form
7243 //
7244 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007245
Douglas Gregorb87786f2010-07-01 17:48:08 +00007246 // C++ [except.spec]p14:
7247 // An implicitly declared special member function (Clause 12) shall have an
7248 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007249
7250 // It is unspecified whether or not an implicit copy assignment operator
7251 // attempts to deduplicate calls to assignment operators of virtual bases are
7252 // made. As such, this exception specification is effectively unspecified.
7253 // Based on a similar decision made for constness in C++0x, we're erring on
7254 // the side of assuming such calls to be made regardless of whether they
7255 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007256 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007257 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007258 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7259 BaseEnd = ClassDecl->bases_end();
7260 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007261 if (Base->isVirtual())
7262 continue;
7263
Douglas Gregora376d102010-07-02 21:50:04 +00007264 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007265 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007266 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7267 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007268 ExceptSpec.CalledDecl(CopyAssign);
7269 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007270
7271 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7272 BaseEnd = ClassDecl->vbases_end();
7273 Base != BaseEnd; ++Base) {
7274 CXXRecordDecl *BaseClassDecl
7275 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7276 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7277 ArgQuals, false, 0))
7278 ExceptSpec.CalledDecl(CopyAssign);
7279 }
7280
Douglas Gregorb87786f2010-07-01 17:48:08 +00007281 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7282 FieldEnd = ClassDecl->field_end();
7283 Field != FieldEnd;
7284 ++Field) {
7285 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007286 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7287 if (CXXMethodDecl *CopyAssign =
7288 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7289 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007290 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007291 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007292
Sean Hunt30de05c2011-05-14 05:23:20 +00007293 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7294}
7295
7296CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7297 // Note: The following rules are largely analoguous to the copy
7298 // constructor rules. Note that virtual bases are not taken into account
7299 // for determining the argument type of the operator. Note also that
7300 // operators taking an object instead of a reference are allowed.
7301
7302 ImplicitExceptionSpecification Spec(Context);
7303 bool Const;
7304 llvm::tie(Spec, Const) =
7305 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7306
7307 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7308 QualType RetType = Context.getLValueReferenceType(ArgType);
7309 if (Const)
7310 ArgType = ArgType.withConst();
7311 ArgType = Context.getLValueReferenceType(ArgType);
7312
Douglas Gregord3c35902010-07-01 16:36:15 +00007313 // An implicitly-declared copy assignment operator is an inline public
7314 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007315 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007316 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007317 SourceLocation ClassLoc = ClassDecl->getLocation();
7318 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007319 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007320 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007321 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007322 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007323 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007324 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007325 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007326 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007327 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007328 CopyAssignment->setImplicit();
7329 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007330
7331 // Add the parameter to the operator.
7332 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007333 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007334 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007335 SC_None,
7336 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00007337 CopyAssignment->setParams(&FromParam, 1);
7338
Douglas Gregora376d102010-07-02 21:50:04 +00007339 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007340 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007341
Douglas Gregor23c94db2010-07-02 17:43:08 +00007342 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007343 PushOnScopeChains(CopyAssignment, S, false);
7344 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007345
Sean Hunt1ccbc542011-06-22 01:05:13 +00007346 // C++0x [class.copy]p18:
7347 // ... If the class definition declares a move constructor or move
7348 // assignment operator, the implicitly declared copy assignment operator is
7349 // defined as deleted; ...
7350 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7351 ClassDecl->hasUserDeclaredMoveAssignment() ||
7352 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007353 CopyAssignment->setDeletedAsWritten();
7354
Douglas Gregord3c35902010-07-01 16:36:15 +00007355 AddOverriddenMethods(ClassDecl, CopyAssignment);
7356 return CopyAssignment;
7357}
7358
Douglas Gregor06a9f362010-05-01 20:49:11 +00007359void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7360 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007361 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007362 CopyAssignOperator->isOverloadedOperator() &&
7363 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007364 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007365 "DefineImplicitCopyAssignment called for wrong function");
7366
7367 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7368
7369 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7370 CopyAssignOperator->setInvalidDecl();
7371 return;
7372 }
7373
7374 CopyAssignOperator->setUsed();
7375
7376 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007377 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007378
7379 // C++0x [class.copy]p30:
7380 // The implicitly-defined or explicitly-defaulted copy assignment operator
7381 // for a non-union class X performs memberwise copy assignment of its
7382 // subobjects. The direct base classes of X are assigned first, in the
7383 // order of their declaration in the base-specifier-list, and then the
7384 // immediate non-static data members of X are assigned, in the order in
7385 // which they were declared in the class definition.
7386
7387 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007388 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007389
7390 // The parameter for the "other" object, which we are copying from.
7391 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7392 Qualifiers OtherQuals = Other->getType().getQualifiers();
7393 QualType OtherRefType = Other->getType();
7394 if (const LValueReferenceType *OtherRef
7395 = OtherRefType->getAs<LValueReferenceType>()) {
7396 OtherRefType = OtherRef->getPointeeType();
7397 OtherQuals = OtherRefType.getQualifiers();
7398 }
7399
7400 // Our location for everything implicitly-generated.
7401 SourceLocation Loc = CopyAssignOperator->getLocation();
7402
7403 // Construct a reference to the "other" object. We'll be using this
7404 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007405 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007406 assert(OtherRef && "Reference to parameter cannot fail!");
7407
7408 // Construct the "this" pointer. We'll be using this throughout the generated
7409 // ASTs.
7410 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7411 assert(This && "Reference to this cannot fail!");
7412
7413 // Assign base classes.
7414 bool Invalid = false;
7415 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7416 E = ClassDecl->bases_end(); Base != E; ++Base) {
7417 // Form the assignment:
7418 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7419 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007420 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007421 Invalid = true;
7422 continue;
7423 }
7424
John McCallf871d0c2010-08-07 06:22:56 +00007425 CXXCastPath BasePath;
7426 BasePath.push_back(Base);
7427
Douglas Gregor06a9f362010-05-01 20:49:11 +00007428 // Construct the "from" expression, which is an implicit cast to the
7429 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007430 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007431 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7432 CK_UncheckedDerivedToBase,
7433 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007434
7435 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007436 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007437
7438 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007439 To = ImpCastExprToType(To.take(),
7440 Context.getCVRQualifiedType(BaseType,
7441 CopyAssignOperator->getTypeQualifiers()),
7442 CK_UncheckedDerivedToBase,
7443 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007444
7445 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007446 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007447 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007448 /*CopyingBaseSubobject=*/true,
7449 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007450 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007451 Diag(CurrentLocation, diag::note_member_synthesized_at)
7452 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7453 CopyAssignOperator->setInvalidDecl();
7454 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007455 }
7456
7457 // Success! Record the copy.
7458 Statements.push_back(Copy.takeAs<Expr>());
7459 }
7460
7461 // \brief Reference to the __builtin_memcpy function.
7462 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007463 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007464 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007465
7466 // Assign non-static members.
7467 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7468 FieldEnd = ClassDecl->field_end();
7469 Field != FieldEnd; ++Field) {
7470 // Check for members of reference type; we can't copy those.
7471 if (Field->getType()->isReferenceType()) {
7472 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7473 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7474 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007475 Diag(CurrentLocation, diag::note_member_synthesized_at)
7476 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007477 Invalid = true;
7478 continue;
7479 }
7480
7481 // Check for members of const-qualified, non-class type.
7482 QualType BaseType = Context.getBaseElementType(Field->getType());
7483 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7485 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7486 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007487 Diag(CurrentLocation, diag::note_member_synthesized_at)
7488 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007489 Invalid = true;
7490 continue;
7491 }
John McCallb77115d2011-06-17 00:18:42 +00007492
7493 // Suppress assigning zero-width bitfields.
7494 if (const Expr *Width = Field->getBitWidth())
7495 if (Width->EvaluateAsInt(Context) == 0)
7496 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007497
7498 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007499 if (FieldType->isIncompleteArrayType()) {
7500 assert(ClassDecl->hasFlexibleArrayMember() &&
7501 "Incomplete array type is not valid");
7502 continue;
7503 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007504
7505 // Build references to the field in the object we're copying from and to.
7506 CXXScopeSpec SS; // Intentionally empty
7507 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7508 LookupMemberName);
7509 MemberLookup.addDecl(*Field);
7510 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007511 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007512 Loc, /*IsArrow=*/false,
7513 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007514 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007515 Loc, /*IsArrow=*/true,
7516 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007517 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7518 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7519
7520 // If the field should be copied with __builtin_memcpy rather than via
7521 // explicit assignments, do so. This optimization only applies for arrays
7522 // of scalars and arrays of class type with trivial copy-assignment
7523 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007524 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007525 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007526 // Compute the size of the memory buffer to be copied.
7527 QualType SizeType = Context.getSizeType();
7528 llvm::APInt Size(Context.getTypeSize(SizeType),
7529 Context.getTypeSizeInChars(BaseType).getQuantity());
7530 for (const ConstantArrayType *Array
7531 = Context.getAsConstantArrayType(FieldType);
7532 Array;
7533 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007534 llvm::APInt ArraySize
7535 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007536 Size *= ArraySize;
7537 }
7538
7539 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007540 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7541 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007542
7543 bool NeedsCollectableMemCpy =
7544 (BaseType->isRecordType() &&
7545 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7546
7547 if (NeedsCollectableMemCpy) {
7548 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007549 // Create a reference to the __builtin_objc_memmove_collectable function.
7550 LookupResult R(*this,
7551 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007552 Loc, LookupOrdinaryName);
7553 LookupName(R, TUScope, true);
7554
7555 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7556 if (!CollectableMemCpy) {
7557 // Something went horribly wrong earlier, and we will have
7558 // complained about it.
7559 Invalid = true;
7560 continue;
7561 }
7562
7563 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7564 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007565 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007566 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7567 }
7568 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007569 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007570 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007571 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7572 LookupOrdinaryName);
7573 LookupName(R, TUScope, true);
7574
7575 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7576 if (!BuiltinMemCpy) {
7577 // Something went horribly wrong earlier, and we will have complained
7578 // about it.
7579 Invalid = true;
7580 continue;
7581 }
7582
7583 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7584 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007585 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007586 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7587 }
7588
John McCallca0408f2010-08-23 06:44:23 +00007589 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007590 CallArgs.push_back(To.takeAs<Expr>());
7591 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007592 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007593 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007594 if (NeedsCollectableMemCpy)
7595 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007596 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007597 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007598 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007599 else
7600 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007601 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007602 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007603 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007604
Douglas Gregor06a9f362010-05-01 20:49:11 +00007605 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7606 Statements.push_back(Call.takeAs<Expr>());
7607 continue;
7608 }
7609
7610 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007611 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007612 To.get(), From.get(),
7613 /*CopyingBaseSubobject=*/false,
7614 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007615 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007616 Diag(CurrentLocation, diag::note_member_synthesized_at)
7617 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7618 CopyAssignOperator->setInvalidDecl();
7619 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007620 }
7621
7622 // Success! Record the copy.
7623 Statements.push_back(Copy.takeAs<Stmt>());
7624 }
7625
7626 if (!Invalid) {
7627 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007628 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007629
John McCall60d7b3a2010-08-24 06:29:42 +00007630 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007631 if (Return.isInvalid())
7632 Invalid = true;
7633 else {
7634 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007635
7636 if (Trap.hasErrorOccurred()) {
7637 Diag(CurrentLocation, diag::note_member_synthesized_at)
7638 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7639 Invalid = true;
7640 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007641 }
7642 }
7643
7644 if (Invalid) {
7645 CopyAssignOperator->setInvalidDecl();
7646 return;
7647 }
7648
John McCall60d7b3a2010-08-24 06:29:42 +00007649 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007650 /*isStmtExpr=*/false);
7651 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7652 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007653
7654 if (ASTMutationListener *L = getASTMutationListener()) {
7655 L->CompletedImplicitDefinition(CopyAssignOperator);
7656 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007657}
7658
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007659Sema::ImplicitExceptionSpecification
7660Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7661 ImplicitExceptionSpecification ExceptSpec(Context);
7662
7663 if (ClassDecl->isInvalidDecl())
7664 return ExceptSpec;
7665
7666 // C++0x [except.spec]p14:
7667 // An implicitly declared special member function (Clause 12) shall have an
7668 // exception-specification. [...]
7669
7670 // It is unspecified whether or not an implicit move assignment operator
7671 // attempts to deduplicate calls to assignment operators of virtual bases are
7672 // made. As such, this exception specification is effectively unspecified.
7673 // Based on a similar decision made for constness in C++0x, we're erring on
7674 // the side of assuming such calls to be made regardless of whether they
7675 // actually happen.
7676 // Note that a move constructor is not implicitly declared when there are
7677 // virtual bases, but it can still be user-declared and explicitly defaulted.
7678 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7679 BaseEnd = ClassDecl->bases_end();
7680 Base != BaseEnd; ++Base) {
7681 if (Base->isVirtual())
7682 continue;
7683
7684 CXXRecordDecl *BaseClassDecl
7685 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7686 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7687 false, 0))
7688 ExceptSpec.CalledDecl(MoveAssign);
7689 }
7690
7691 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7692 BaseEnd = ClassDecl->vbases_end();
7693 Base != BaseEnd; ++Base) {
7694 CXXRecordDecl *BaseClassDecl
7695 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7696 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7697 false, 0))
7698 ExceptSpec.CalledDecl(MoveAssign);
7699 }
7700
7701 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7702 FieldEnd = ClassDecl->field_end();
7703 Field != FieldEnd;
7704 ++Field) {
7705 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7706 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7707 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7708 false, 0))
7709 ExceptSpec.CalledDecl(MoveAssign);
7710 }
7711 }
7712
7713 return ExceptSpec;
7714}
7715
7716CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7717 // Note: The following rules are largely analoguous to the move
7718 // constructor rules.
7719
7720 ImplicitExceptionSpecification Spec(
7721 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7722
7723 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7724 QualType RetType = Context.getLValueReferenceType(ArgType);
7725 ArgType = Context.getRValueReferenceType(ArgType);
7726
7727 // An implicitly-declared move assignment operator is an inline public
7728 // member of its class.
7729 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7730 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7731 SourceLocation ClassLoc = ClassDecl->getLocation();
7732 DeclarationNameInfo NameInfo(Name, ClassLoc);
7733 CXXMethodDecl *MoveAssignment
7734 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7735 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7736 /*TInfo=*/0, /*isStatic=*/false,
7737 /*StorageClassAsWritten=*/SC_None,
7738 /*isInline=*/true,
7739 /*isConstexpr=*/false,
7740 SourceLocation());
7741 MoveAssignment->setAccess(AS_public);
7742 MoveAssignment->setDefaulted();
7743 MoveAssignment->setImplicit();
7744 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7745
7746 // Add the parameter to the operator.
7747 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7748 ClassLoc, ClassLoc, /*Id=*/0,
7749 ArgType, /*TInfo=*/0,
7750 SC_None,
7751 SC_None, 0);
7752 MoveAssignment->setParams(&FromParam, 1);
7753
7754 // Note that we have added this copy-assignment operator.
7755 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7756
7757 // C++0x [class.copy]p9:
7758 // If the definition of a class X does not explicitly declare a move
7759 // assignment operator, one will be implicitly declared as defaulted if and
7760 // only if:
7761 // [...]
7762 // - the move assignment operator would not be implicitly defined as
7763 // deleted.
7764 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7765 // Cache this result so that we don't try to generate this over and over
7766 // on every lookup, leaking memory and wasting time.
7767 ClassDecl->setFailedImplicitMoveAssignment();
7768 return 0;
7769 }
7770
7771 if (Scope *S = getScopeForContext(ClassDecl))
7772 PushOnScopeChains(MoveAssignment, S, false);
7773 ClassDecl->addDecl(MoveAssignment);
7774
7775 AddOverriddenMethods(ClassDecl, MoveAssignment);
7776 return MoveAssignment;
7777}
7778
7779void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7780 CXXMethodDecl *MoveAssignOperator) {
7781 assert((MoveAssignOperator->isDefaulted() &&
7782 MoveAssignOperator->isOverloadedOperator() &&
7783 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7784 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7785 "DefineImplicitMoveAssignment called for wrong function");
7786
7787 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7788
7789 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7790 MoveAssignOperator->setInvalidDecl();
7791 return;
7792 }
7793
7794 MoveAssignOperator->setUsed();
7795
7796 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7797 DiagnosticErrorTrap Trap(Diags);
7798
7799 // C++0x [class.copy]p28:
7800 // The implicitly-defined or move assignment operator for a non-union class
7801 // X performs memberwise move assignment of its subobjects. The direct base
7802 // classes of X are assigned first, in the order of their declaration in the
7803 // base-specifier-list, and then the immediate non-static data members of X
7804 // are assigned, in the order in which they were declared in the class
7805 // definition.
7806
7807 // The statements that form the synthesized function body.
7808 ASTOwningVector<Stmt*> Statements(*this);
7809
7810 // The parameter for the "other" object, which we are move from.
7811 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7812 QualType OtherRefType = Other->getType()->
7813 getAs<RValueReferenceType>()->getPointeeType();
7814 assert(OtherRefType.getQualifiers() == 0 &&
7815 "Bad argument type of defaulted move assignment");
7816
7817 // Our location for everything implicitly-generated.
7818 SourceLocation Loc = MoveAssignOperator->getLocation();
7819
7820 // Construct a reference to the "other" object. We'll be using this
7821 // throughout the generated ASTs.
7822 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7823 assert(OtherRef && "Reference to parameter cannot fail!");
7824 // Cast to rvalue.
7825 OtherRef = CastForMoving(*this, OtherRef);
7826
7827 // Construct the "this" pointer. We'll be using this throughout the generated
7828 // ASTs.
7829 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7830 assert(This && "Reference to this cannot fail!");
7831
7832 // Assign base classes.
7833 bool Invalid = false;
7834 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7835 E = ClassDecl->bases_end(); Base != E; ++Base) {
7836 // Form the assignment:
7837 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7838 QualType BaseType = Base->getType().getUnqualifiedType();
7839 if (!BaseType->isRecordType()) {
7840 Invalid = true;
7841 continue;
7842 }
7843
7844 CXXCastPath BasePath;
7845 BasePath.push_back(Base);
7846
7847 // Construct the "from" expression, which is an implicit cast to the
7848 // appropriately-qualified base type.
7849 Expr *From = OtherRef;
7850 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00007851 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007852
7853 // Dereference "this".
7854 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7855
7856 // Implicitly cast "this" to the appropriately-qualified base type.
7857 To = ImpCastExprToType(To.take(),
7858 Context.getCVRQualifiedType(BaseType,
7859 MoveAssignOperator->getTypeQualifiers()),
7860 CK_UncheckedDerivedToBase,
7861 VK_LValue, &BasePath);
7862
7863 // Build the move.
7864 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7865 To.get(), From,
7866 /*CopyingBaseSubobject=*/true,
7867 /*Copying=*/false);
7868 if (Move.isInvalid()) {
7869 Diag(CurrentLocation, diag::note_member_synthesized_at)
7870 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7871 MoveAssignOperator->setInvalidDecl();
7872 return;
7873 }
7874
7875 // Success! Record the move.
7876 Statements.push_back(Move.takeAs<Expr>());
7877 }
7878
7879 // \brief Reference to the __builtin_memcpy function.
7880 Expr *BuiltinMemCpyRef = 0;
7881 // \brief Reference to the __builtin_objc_memmove_collectable function.
7882 Expr *CollectableMemCpyRef = 0;
7883
7884 // Assign non-static members.
7885 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7886 FieldEnd = ClassDecl->field_end();
7887 Field != FieldEnd; ++Field) {
7888 // Check for members of reference type; we can't move those.
7889 if (Field->getType()->isReferenceType()) {
7890 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7891 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7892 Diag(Field->getLocation(), diag::note_declared_at);
7893 Diag(CurrentLocation, diag::note_member_synthesized_at)
7894 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7895 Invalid = true;
7896 continue;
7897 }
7898
7899 // Check for members of const-qualified, non-class type.
7900 QualType BaseType = Context.getBaseElementType(Field->getType());
7901 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7902 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7903 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7904 Diag(Field->getLocation(), diag::note_declared_at);
7905 Diag(CurrentLocation, diag::note_member_synthesized_at)
7906 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7907 Invalid = true;
7908 continue;
7909 }
7910
7911 // Suppress assigning zero-width bitfields.
7912 if (const Expr *Width = Field->getBitWidth())
7913 if (Width->EvaluateAsInt(Context) == 0)
7914 continue;
7915
7916 QualType FieldType = Field->getType().getNonReferenceType();
7917 if (FieldType->isIncompleteArrayType()) {
7918 assert(ClassDecl->hasFlexibleArrayMember() &&
7919 "Incomplete array type is not valid");
7920 continue;
7921 }
7922
7923 // Build references to the field in the object we're copying from and to.
7924 CXXScopeSpec SS; // Intentionally empty
7925 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7926 LookupMemberName);
7927 MemberLookup.addDecl(*Field);
7928 MemberLookup.resolveKind();
7929 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7930 Loc, /*IsArrow=*/false,
7931 SS, 0, MemberLookup, 0);
7932 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7933 Loc, /*IsArrow=*/true,
7934 SS, 0, MemberLookup, 0);
7935 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7936 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7937
7938 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7939 "Member reference with rvalue base must be rvalue except for reference "
7940 "members, which aren't allowed for move assignment.");
7941
7942 // If the field should be copied with __builtin_memcpy rather than via
7943 // explicit assignments, do so. This optimization only applies for arrays
7944 // of scalars and arrays of class type with trivial move-assignment
7945 // operators.
7946 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7947 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7948 // Compute the size of the memory buffer to be copied.
7949 QualType SizeType = Context.getSizeType();
7950 llvm::APInt Size(Context.getTypeSize(SizeType),
7951 Context.getTypeSizeInChars(BaseType).getQuantity());
7952 for (const ConstantArrayType *Array
7953 = Context.getAsConstantArrayType(FieldType);
7954 Array;
7955 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7956 llvm::APInt ArraySize
7957 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7958 Size *= ArraySize;
7959 }
7960
Douglas Gregor45d3d712011-09-01 02:09:07 +00007961 // Take the address of the field references for "from" and "to". We
7962 // directly construct UnaryOperators here because semantic analysis
7963 // does not permit us to take the address of an xvalue.
7964 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7965 Context.getPointerType(From.get()->getType()),
7966 VK_RValue, OK_Ordinary, Loc);
7967 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7968 Context.getPointerType(To.get()->getType()),
7969 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007970
7971 bool NeedsCollectableMemCpy =
7972 (BaseType->isRecordType() &&
7973 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7974
7975 if (NeedsCollectableMemCpy) {
7976 if (!CollectableMemCpyRef) {
7977 // Create a reference to the __builtin_objc_memmove_collectable function.
7978 LookupResult R(*this,
7979 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7980 Loc, LookupOrdinaryName);
7981 LookupName(R, TUScope, true);
7982
7983 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7984 if (!CollectableMemCpy) {
7985 // Something went horribly wrong earlier, and we will have
7986 // complained about it.
7987 Invalid = true;
7988 continue;
7989 }
7990
7991 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7992 CollectableMemCpy->getType(),
7993 VK_LValue, Loc, 0).take();
7994 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7995 }
7996 }
7997 // Create a reference to the __builtin_memcpy builtin function.
7998 else if (!BuiltinMemCpyRef) {
7999 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8000 LookupOrdinaryName);
8001 LookupName(R, TUScope, true);
8002
8003 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8004 if (!BuiltinMemCpy) {
8005 // Something went horribly wrong earlier, and we will have complained
8006 // about it.
8007 Invalid = true;
8008 continue;
8009 }
8010
8011 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8012 BuiltinMemCpy->getType(),
8013 VK_LValue, Loc, 0).take();
8014 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8015 }
8016
8017 ASTOwningVector<Expr*> CallArgs(*this);
8018 CallArgs.push_back(To.takeAs<Expr>());
8019 CallArgs.push_back(From.takeAs<Expr>());
8020 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8021 ExprResult Call = ExprError();
8022 if (NeedsCollectableMemCpy)
8023 Call = ActOnCallExpr(/*Scope=*/0,
8024 CollectableMemCpyRef,
8025 Loc, move_arg(CallArgs),
8026 Loc);
8027 else
8028 Call = ActOnCallExpr(/*Scope=*/0,
8029 BuiltinMemCpyRef,
8030 Loc, move_arg(CallArgs),
8031 Loc);
8032
8033 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8034 Statements.push_back(Call.takeAs<Expr>());
8035 continue;
8036 }
8037
8038 // Build the move of this field.
8039 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8040 To.get(), From.get(),
8041 /*CopyingBaseSubobject=*/false,
8042 /*Copying=*/false);
8043 if (Move.isInvalid()) {
8044 Diag(CurrentLocation, diag::note_member_synthesized_at)
8045 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8046 MoveAssignOperator->setInvalidDecl();
8047 return;
8048 }
8049
8050 // Success! Record the copy.
8051 Statements.push_back(Move.takeAs<Stmt>());
8052 }
8053
8054 if (!Invalid) {
8055 // Add a "return *this;"
8056 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8057
8058 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8059 if (Return.isInvalid())
8060 Invalid = true;
8061 else {
8062 Statements.push_back(Return.takeAs<Stmt>());
8063
8064 if (Trap.hasErrorOccurred()) {
8065 Diag(CurrentLocation, diag::note_member_synthesized_at)
8066 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8067 Invalid = true;
8068 }
8069 }
8070 }
8071
8072 if (Invalid) {
8073 MoveAssignOperator->setInvalidDecl();
8074 return;
8075 }
8076
8077 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8078 /*isStmtExpr=*/false);
8079 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8080 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8081
8082 if (ASTMutationListener *L = getASTMutationListener()) {
8083 L->CompletedImplicitDefinition(MoveAssignOperator);
8084 }
8085}
8086
Sean Hunt49634cf2011-05-13 06:10:58 +00008087std::pair<Sema::ImplicitExceptionSpecification, bool>
8088Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008089 if (ClassDecl->isInvalidDecl())
8090 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8091
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008092 // C++ [class.copy]p5:
8093 // The implicitly-declared copy constructor for a class X will
8094 // have the form
8095 //
8096 // X::X(const X&)
8097 //
8098 // if
Sean Huntc530d172011-06-10 04:44:37 +00008099 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008100 bool HasConstCopyConstructor = true;
8101
8102 // -- each direct or virtual base class B of X has a copy
8103 // constructor whose first parameter is of type const B& or
8104 // const volatile B&, and
8105 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8106 BaseEnd = ClassDecl->bases_end();
8107 HasConstCopyConstructor && Base != BaseEnd;
8108 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008109 // Virtual bases are handled below.
8110 if (Base->isVirtual())
8111 continue;
8112
Douglas Gregor22584312010-07-02 23:41:54 +00008113 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008114 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008115 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8116 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008117 }
8118
8119 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8120 BaseEnd = ClassDecl->vbases_end();
8121 HasConstCopyConstructor && Base != BaseEnd;
8122 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008123 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008124 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008125 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8126 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008127 }
8128
8129 // -- for all the nonstatic data members of X that are of a
8130 // class type M (or array thereof), each such class type
8131 // has a copy constructor whose first parameter is of type
8132 // const M& or const volatile M&.
8133 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8134 FieldEnd = ClassDecl->field_end();
8135 HasConstCopyConstructor && Field != FieldEnd;
8136 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008137 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008138 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008139 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8140 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008141 }
8142 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008143 // Otherwise, the implicitly declared copy constructor will have
8144 // the form
8145 //
8146 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008147
Douglas Gregor0d405db2010-07-01 20:59:04 +00008148 // C++ [except.spec]p14:
8149 // An implicitly declared special member function (Clause 12) shall have an
8150 // exception-specification. [...]
8151 ImplicitExceptionSpecification ExceptSpec(Context);
8152 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8153 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8154 BaseEnd = ClassDecl->bases_end();
8155 Base != BaseEnd;
8156 ++Base) {
8157 // Virtual bases are handled below.
8158 if (Base->isVirtual())
8159 continue;
8160
Douglas Gregor22584312010-07-02 23:41:54 +00008161 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008162 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008163 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008164 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008165 ExceptSpec.CalledDecl(CopyConstructor);
8166 }
8167 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8168 BaseEnd = ClassDecl->vbases_end();
8169 Base != BaseEnd;
8170 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008171 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008172 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008173 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008174 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008175 ExceptSpec.CalledDecl(CopyConstructor);
8176 }
8177 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8178 FieldEnd = ClassDecl->field_end();
8179 Field != FieldEnd;
8180 ++Field) {
8181 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008182 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8183 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008184 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008185 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008186 }
8187 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008188
Sean Hunt49634cf2011-05-13 06:10:58 +00008189 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8190}
8191
8192CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8193 CXXRecordDecl *ClassDecl) {
8194 // C++ [class.copy]p4:
8195 // If the class definition does not explicitly declare a copy
8196 // constructor, one is declared implicitly.
8197
8198 ImplicitExceptionSpecification Spec(Context);
8199 bool Const;
8200 llvm::tie(Spec, Const) =
8201 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8202
8203 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8204 QualType ArgType = ClassType;
8205 if (Const)
8206 ArgType = ArgType.withConst();
8207 ArgType = Context.getLValueReferenceType(ArgType);
8208
8209 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8210
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008211 DeclarationName Name
8212 = Context.DeclarationNames.getCXXConstructorName(
8213 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008214 SourceLocation ClassLoc = ClassDecl->getLocation();
8215 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008216
8217 // An implicitly-declared copy constructor is an inline public
8218 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008219 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008220 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008221 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00008222 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008223 /*TInfo=*/0,
8224 /*isExplicit=*/false,
8225 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008226 /*isImplicitlyDeclared=*/true,
8227 // FIXME: apply the rules for definitions here
8228 /*isConstexpr=*/false);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008229 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008230 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008231 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8232
Douglas Gregor22584312010-07-02 23:41:54 +00008233 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008234 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8235
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008236 // Add the parameter to the constructor.
8237 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008238 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008239 /*IdentifierInfo=*/0,
8240 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008241 SC_None,
8242 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008243 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00008244
Douglas Gregor23c94db2010-07-02 17:43:08 +00008245 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008246 PushOnScopeChains(CopyConstructor, S, false);
8247 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008248
Sean Hunt1ccbc542011-06-22 01:05:13 +00008249 // C++0x [class.copy]p7:
8250 // ... If the class definition declares a move constructor or move
8251 // assignment operator, the implicitly declared constructor is defined as
8252 // deleted; ...
8253 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8254 ClassDecl->hasUserDeclaredMoveAssignment() ||
8255 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008256 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008257
8258 return CopyConstructor;
8259}
8260
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008261void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008262 CXXConstructorDecl *CopyConstructor) {
8263 assert((CopyConstructor->isDefaulted() &&
8264 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008265 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008266 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008267
Anders Carlsson63010a72010-04-23 16:24:12 +00008268 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008269 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008270
Douglas Gregor39957dc2010-05-01 15:04:51 +00008271 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008272 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008273
Sean Huntcbb67482011-01-08 20:30:50 +00008274 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008275 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008276 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008277 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008278 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008279 } else {
8280 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8281 CopyConstructor->getLocation(),
8282 MultiStmtArg(*this, 0, 0),
8283 /*isStmtExpr=*/false)
8284 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008285 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008286
8287 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008288
8289 if (ASTMutationListener *L = getASTMutationListener()) {
8290 L->CompletedImplicitDefinition(CopyConstructor);
8291 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008292}
8293
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008294Sema::ImplicitExceptionSpecification
8295Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8296 // C++ [except.spec]p14:
8297 // An implicitly declared special member function (Clause 12) shall have an
8298 // exception-specification. [...]
8299 ImplicitExceptionSpecification ExceptSpec(Context);
8300 if (ClassDecl->isInvalidDecl())
8301 return ExceptSpec;
8302
8303 // Direct base-class constructors.
8304 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8305 BEnd = ClassDecl->bases_end();
8306 B != BEnd; ++B) {
8307 if (B->isVirtual()) // Handled below.
8308 continue;
8309
8310 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8311 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8312 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8313 // If this is a deleted function, add it anyway. This might be conformant
8314 // with the standard. This might not. I'm not sure. It might not matter.
8315 if (Constructor)
8316 ExceptSpec.CalledDecl(Constructor);
8317 }
8318 }
8319
8320 // Virtual base-class constructors.
8321 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8322 BEnd = ClassDecl->vbases_end();
8323 B != BEnd; ++B) {
8324 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8325 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8326 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8327 // If this is a deleted function, add it anyway. This might be conformant
8328 // with the standard. This might not. I'm not sure. It might not matter.
8329 if (Constructor)
8330 ExceptSpec.CalledDecl(Constructor);
8331 }
8332 }
8333
8334 // Field constructors.
8335 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8336 FEnd = ClassDecl->field_end();
8337 F != FEnd; ++F) {
8338 if (F->hasInClassInitializer()) {
8339 if (Expr *E = F->getInClassInitializer())
8340 ExceptSpec.CalledExpr(E);
8341 else if (!F->isInvalidDecl())
8342 ExceptSpec.SetDelayed();
8343 } else if (const RecordType *RecordTy
8344 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8345 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8346 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8347 // If this is a deleted function, add it anyway. This might be conformant
8348 // with the standard. This might not. I'm not sure. It might not matter.
8349 // In particular, the problem is that this function never gets called. It
8350 // might just be ill-formed because this function attempts to refer to
8351 // a deleted function here.
8352 if (Constructor)
8353 ExceptSpec.CalledDecl(Constructor);
8354 }
8355 }
8356
8357 return ExceptSpec;
8358}
8359
8360CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8361 CXXRecordDecl *ClassDecl) {
8362 ImplicitExceptionSpecification Spec(
8363 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8364
8365 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8366 QualType ArgType = Context.getRValueReferenceType(ClassType);
8367
8368 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8369
8370 DeclarationName Name
8371 = Context.DeclarationNames.getCXXConstructorName(
8372 Context.getCanonicalType(ClassType));
8373 SourceLocation ClassLoc = ClassDecl->getLocation();
8374 DeclarationNameInfo NameInfo(Name, ClassLoc);
8375
8376 // C++0x [class.copy]p11:
8377 // An implicitly-declared copy/move constructor is an inline public
8378 // member of its class.
8379 CXXConstructorDecl *MoveConstructor
8380 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8381 Context.getFunctionType(Context.VoidTy,
8382 &ArgType, 1, EPI),
8383 /*TInfo=*/0,
8384 /*isExplicit=*/false,
8385 /*isInline=*/true,
8386 /*isImplicitlyDeclared=*/true,
8387 // FIXME: apply the rules for definitions here
8388 /*isConstexpr=*/false);
8389 MoveConstructor->setAccess(AS_public);
8390 MoveConstructor->setDefaulted();
8391 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8392
8393 // Add the parameter to the constructor.
8394 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8395 ClassLoc, ClassLoc,
8396 /*IdentifierInfo=*/0,
8397 ArgType, /*TInfo=*/0,
8398 SC_None,
8399 SC_None, 0);
8400 MoveConstructor->setParams(&FromParam, 1);
8401
8402 // C++0x [class.copy]p9:
8403 // If the definition of a class X does not explicitly declare a move
8404 // constructor, one will be implicitly declared as defaulted if and only if:
8405 // [...]
8406 // - the move constructor would not be implicitly defined as deleted.
8407 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8408 // Cache this result so that we don't try to generate this over and over
8409 // on every lookup, leaking memory and wasting time.
8410 ClassDecl->setFailedImplicitMoveConstructor();
8411 return 0;
8412 }
8413
8414 // Note that we have declared this constructor.
8415 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8416
8417 if (Scope *S = getScopeForContext(ClassDecl))
8418 PushOnScopeChains(MoveConstructor, S, false);
8419 ClassDecl->addDecl(MoveConstructor);
8420
8421 return MoveConstructor;
8422}
8423
8424void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8425 CXXConstructorDecl *MoveConstructor) {
8426 assert((MoveConstructor->isDefaulted() &&
8427 MoveConstructor->isMoveConstructor() &&
8428 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8429 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8430
8431 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8432 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8433
8434 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8435 DiagnosticErrorTrap Trap(Diags);
8436
8437 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8438 Trap.hasErrorOccurred()) {
8439 Diag(CurrentLocation, diag::note_member_synthesized_at)
8440 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8441 MoveConstructor->setInvalidDecl();
8442 } else {
8443 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8444 MoveConstructor->getLocation(),
8445 MultiStmtArg(*this, 0, 0),
8446 /*isStmtExpr=*/false)
8447 .takeAs<Stmt>());
8448 }
8449
8450 MoveConstructor->setUsed();
8451
8452 if (ASTMutationListener *L = getASTMutationListener()) {
8453 L->CompletedImplicitDefinition(MoveConstructor);
8454 }
8455}
8456
John McCall60d7b3a2010-08-24 06:29:42 +00008457ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008458Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008459 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008460 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008461 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008462 unsigned ConstructKind,
8463 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008464 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008465
Douglas Gregor2f599792010-04-02 18:24:57 +00008466 // C++0x [class.copy]p34:
8467 // When certain criteria are met, an implementation is allowed to
8468 // omit the copy/move construction of a class object, even if the
8469 // copy/move constructor and/or destructor for the object have
8470 // side effects. [...]
8471 // - when a temporary class object that has not been bound to a
8472 // reference (12.2) would be copied/moved to a class object
8473 // with the same cv-unqualified type, the copy/move operation
8474 // can be omitted by constructing the temporary object
8475 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008476 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008477 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008478 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008479 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008480 }
Mike Stump1eb44332009-09-09 15:08:12 +00008481
8482 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008483 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008484 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008485}
8486
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008487/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8488/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008489ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008490Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8491 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008492 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008493 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008494 unsigned ConstructKind,
8495 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008496 unsigned NumExprs = ExprArgs.size();
8497 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008498
Nick Lewycky909a70d2011-03-25 01:44:32 +00008499 for (specific_attr_iterator<NonNullAttr>
8500 i = Constructor->specific_attr_begin<NonNullAttr>(),
8501 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8502 const NonNullAttr *NonNull = *i;
8503 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8504 }
8505
Douglas Gregor7edfb692009-11-23 12:27:39 +00008506 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008507 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00008508 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00008509 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008510 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8511 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008512}
8513
Mike Stump1eb44332009-09-09 15:08:12 +00008514bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008515 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00008516 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008517 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008518 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008519 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008520 move(Exprs), false, CXXConstructExpr::CK_Complete,
8521 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008522 if (TempResult.isInvalid())
8523 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008524
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008525 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008526 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008527 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008528 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008529 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008530
Anders Carlssonfe2de492009-08-25 05:18:00 +00008531 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008532}
8533
John McCall68c6c9a2010-02-02 09:10:11 +00008534void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008535 if (VD->isInvalidDecl()) return;
8536
John McCall68c6c9a2010-02-02 09:10:11 +00008537 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008538 if (ClassDecl->isInvalidDecl()) return;
8539 if (ClassDecl->hasTrivialDestructor()) return;
8540 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008541
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008542 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8543 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8544 CheckDestructorAccess(VD->getLocation(), Destructor,
8545 PDiag(diag::err_access_dtor_var)
8546 << VD->getDeclName()
8547 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008548
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008549 if (!VD->hasGlobalStorage()) return;
8550
8551 // Emit warning for non-trivial dtor in global scope (a real global,
8552 // class-static, function-static).
8553 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8554
8555 // TODO: this should be re-enabled for static locals by !CXAAtExit
8556 if (!VD->isStaticLocal())
8557 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008558}
8559
Mike Stump1eb44332009-09-09 15:08:12 +00008560/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008561/// ActOnDeclarator, when a C++ direct initializer is present.
8562/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008563void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008564 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008565 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008566 SourceLocation RParenLoc,
8567 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00008568 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008569
8570 // If there is no declaration, there was an error parsing it. Just ignore
8571 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008572 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008573 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008574
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008575 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8576 if (!VDecl) {
8577 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8578 RealDecl->setInvalidDecl();
8579 return;
8580 }
8581
Richard Smith34b41d92011-02-20 03:19:35 +00008582 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8583 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008584 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8585 if (Exprs.size() > 1) {
8586 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8587 diag::err_auto_var_init_multiple_expressions)
8588 << VDecl->getDeclName() << VDecl->getType()
8589 << VDecl->getSourceRange();
8590 RealDecl->setInvalidDecl();
8591 return;
8592 }
8593
8594 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008595 TypeSourceInfo *DeducedType = 0;
8596 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008597 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8598 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8599 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008600 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008601 RealDecl->setInvalidDecl();
8602 return;
8603 }
Richard Smitha085da82011-03-17 16:11:59 +00008604 VDecl->setTypeSourceInfo(DeducedType);
8605 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008606
John McCallf85e1932011-06-15 23:02:42 +00008607 // In ARC, infer lifetime.
8608 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8609 VDecl->setInvalidDecl();
8610
Richard Smith34b41d92011-02-20 03:19:35 +00008611 // If this is a redeclaration, check that the type we just deduced matches
8612 // the previously declared type.
8613 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8614 MergeVarDeclTypes(VDecl, Old);
8615 }
8616
Douglas Gregor83ddad32009-08-26 21:14:46 +00008617 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008618 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008619 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8620 //
8621 // Clients that want to distinguish between the two forms, can check for
8622 // direct initializer using VarDecl::hasCXXDirectInitializer().
8623 // A major benefit is that clients that don't particularly care about which
8624 // exactly form was it (like the CodeGen) can handle both cases without
8625 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008626
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008627 // C++ 8.5p11:
8628 // The form of initialization (using parentheses or '=') is generally
8629 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008630 // class type.
8631
Douglas Gregor4dffad62010-02-11 22:55:30 +00008632 if (!VDecl->getType()->isDependentType() &&
8633 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00008634 diag::err_typecheck_decl_incomplete_type)) {
8635 VDecl->setInvalidDecl();
8636 return;
8637 }
8638
Douglas Gregor90f93822009-12-22 22:17:25 +00008639 // The variable can not have an abstract class type.
8640 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8641 diag::err_abstract_type_in_decl,
8642 AbstractVariableType))
8643 VDecl->setInvalidDecl();
8644
Sebastian Redl31310a22010-02-01 20:16:42 +00008645 const VarDecl *Def;
8646 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00008647 Diag(VDecl->getLocation(), diag::err_redefinition)
8648 << VDecl->getDeclName();
8649 Diag(Def->getLocation(), diag::note_previous_definition);
8650 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008651 return;
8652 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00008653
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008654 // C++ [class.static.data]p4
8655 // If a static data member is of const integral or const
8656 // enumeration type, its declaration in the class definition can
8657 // specify a constant-initializer which shall be an integral
8658 // constant expression (5.19). In that case, the member can appear
8659 // in integral constant expressions. The member shall still be
8660 // defined in a namespace scope if it is used in the program and the
8661 // namespace scope definition shall not contain an initializer.
8662 //
8663 // We already performed a redefinition check above, but for static
8664 // data members we also need to check whether there was an in-class
8665 // declaration with an initializer.
8666 const VarDecl* PrevInit = 0;
8667 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8668 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8669 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8670 return;
8671 }
8672
Douglas Gregora31040f2010-12-16 01:31:22 +00008673 bool IsDependent = false;
8674 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8675 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8676 VDecl->setInvalidDecl();
8677 return;
8678 }
8679
8680 if (Exprs.get()[I]->isTypeDependent())
8681 IsDependent = true;
8682 }
8683
Douglas Gregor4dffad62010-02-11 22:55:30 +00008684 // If either the declaration has a dependent type or if any of the
8685 // expressions is type-dependent, we represent the initialization
8686 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00008687 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00008688 // Let clients know that initialization was done with a direct initializer.
8689 VDecl->setCXXDirectInitializer(true);
8690
8691 // Store the initialization expressions as a ParenListExpr.
8692 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00008693 VDecl->setInit(new (Context) ParenListExpr(
8694 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8695 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00008696 return;
8697 }
Douglas Gregor90f93822009-12-22 22:17:25 +00008698
8699 // Capture the variable that is being initialized and the style of
8700 // initialization.
8701 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8702
8703 // FIXME: Poor source location information.
8704 InitializationKind Kind
8705 = InitializationKind::CreateDirect(VDecl->getLocation(),
8706 LParenLoc, RParenLoc);
8707
8708 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00008709 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00008710 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00008711 if (Result.isInvalid()) {
8712 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008713 return;
8714 }
John McCallb4eb64d2010-10-08 02:01:28 +00008715
8716 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00008717
Douglas Gregor53c374f2010-12-07 00:41:46 +00008718 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00008719 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008720 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008721
John McCall2998d6b2011-01-19 11:48:09 +00008722 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008723}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008724
Douglas Gregor39da0b82009-09-09 23:08:42 +00008725/// \brief Given a constructor and the set of arguments provided for the
8726/// constructor, convert the arguments and add any required default arguments
8727/// to form a proper call to this constructor.
8728///
8729/// \returns true if an error occurred, false otherwise.
8730bool
8731Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8732 MultiExprArg ArgsPtr,
8733 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00008734 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008735 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8736 unsigned NumArgs = ArgsPtr.size();
8737 Expr **Args = (Expr **)ArgsPtr.get();
8738
8739 const FunctionProtoType *Proto
8740 = Constructor->getType()->getAs<FunctionProtoType>();
8741 assert(Proto && "Constructor without a prototype?");
8742 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008743
8744 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008745 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008746 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008747 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008748 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008749
8750 VariadicCallType CallType =
8751 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008752 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008753 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8754 Proto, 0, Args, NumArgs, AllArgs,
8755 CallType);
8756 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8757 ConvertedArgs.push_back(AllArgs[i]);
8758 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008759}
8760
Anders Carlsson20d45d22009-12-12 00:32:00 +00008761static inline bool
8762CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8763 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008764 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00008765 if (isa<NamespaceDecl>(DC)) {
8766 return SemaRef.Diag(FnDecl->getLocation(),
8767 diag::err_operator_new_delete_declared_in_namespace)
8768 << FnDecl->getDeclName();
8769 }
8770
8771 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00008772 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008773 return SemaRef.Diag(FnDecl->getLocation(),
8774 diag::err_operator_new_delete_declared_static)
8775 << FnDecl->getDeclName();
8776 }
8777
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00008778 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00008779}
8780
Anders Carlsson156c78e2009-12-13 17:53:43 +00008781static inline bool
8782CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8783 CanQualType ExpectedResultType,
8784 CanQualType ExpectedFirstParamType,
8785 unsigned DependentParamTypeDiag,
8786 unsigned InvalidParamTypeDiag) {
8787 QualType ResultType =
8788 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8789
8790 // Check that the result type is not dependent.
8791 if (ResultType->isDependentType())
8792 return SemaRef.Diag(FnDecl->getLocation(),
8793 diag::err_operator_new_delete_dependent_result_type)
8794 << FnDecl->getDeclName() << ExpectedResultType;
8795
8796 // Check that the result type is what we expect.
8797 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8798 return SemaRef.Diag(FnDecl->getLocation(),
8799 diag::err_operator_new_delete_invalid_result_type)
8800 << FnDecl->getDeclName() << ExpectedResultType;
8801
8802 // A function template must have at least 2 parameters.
8803 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8804 return SemaRef.Diag(FnDecl->getLocation(),
8805 diag::err_operator_new_delete_template_too_few_parameters)
8806 << FnDecl->getDeclName();
8807
8808 // The function decl must have at least 1 parameter.
8809 if (FnDecl->getNumParams() == 0)
8810 return SemaRef.Diag(FnDecl->getLocation(),
8811 diag::err_operator_new_delete_too_few_parameters)
8812 << FnDecl->getDeclName();
8813
8814 // Check the the first parameter type is not dependent.
8815 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8816 if (FirstParamType->isDependentType())
8817 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8818 << FnDecl->getDeclName() << ExpectedFirstParamType;
8819
8820 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00008821 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00008822 ExpectedFirstParamType)
8823 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8824 << FnDecl->getDeclName() << ExpectedFirstParamType;
8825
8826 return false;
8827}
8828
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008829static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00008830CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008831 // C++ [basic.stc.dynamic.allocation]p1:
8832 // A program is ill-formed if an allocation function is declared in a
8833 // namespace scope other than global scope or declared static in global
8834 // scope.
8835 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8836 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00008837
8838 CanQualType SizeTy =
8839 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8840
8841 // C++ [basic.stc.dynamic.allocation]p1:
8842 // The return type shall be void*. The first parameter shall have type
8843 // std::size_t.
8844 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8845 SizeTy,
8846 diag::err_operator_new_dependent_param_type,
8847 diag::err_operator_new_param_type))
8848 return true;
8849
8850 // C++ [basic.stc.dynamic.allocation]p1:
8851 // The first parameter shall not have an associated default argument.
8852 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00008853 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00008854 diag::err_operator_new_default_arg)
8855 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8856
8857 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00008858}
8859
8860static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008861CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8862 // C++ [basic.stc.dynamic.deallocation]p1:
8863 // A program is ill-formed if deallocation functions are declared in a
8864 // namespace scope other than global scope or declared static in global
8865 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00008866 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8867 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008868
8869 // C++ [basic.stc.dynamic.deallocation]p2:
8870 // Each deallocation function shall return void and its first parameter
8871 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00008872 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8873 SemaRef.Context.VoidPtrTy,
8874 diag::err_operator_delete_dependent_param_type,
8875 diag::err_operator_delete_param_type))
8876 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008877
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008878 return false;
8879}
8880
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008881/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8882/// of this overloaded operator is well-formed. If so, returns false;
8883/// otherwise, emits appropriate diagnostics and returns true.
8884bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008885 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008886 "Expected an overloaded operator declaration");
8887
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008888 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8889
Mike Stump1eb44332009-09-09 15:08:12 +00008890 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008891 // The allocation and deallocation functions, operator new,
8892 // operator new[], operator delete and operator delete[], are
8893 // described completely in 3.7.3. The attributes and restrictions
8894 // found in the rest of this subclause do not apply to them unless
8895 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00008896 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008897 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00008898
Anders Carlssona3ccda52009-12-12 00:26:23 +00008899 if (Op == OO_New || Op == OO_Array_New)
8900 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008901
8902 // C++ [over.oper]p6:
8903 // An operator function shall either be a non-static member
8904 // function or be a non-member function and have at least one
8905 // parameter whose type is a class, a reference to a class, an
8906 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008907 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8908 if (MethodDecl->isStatic())
8909 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008910 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008911 } else {
8912 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008913 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8914 ParamEnd = FnDecl->param_end();
8915 Param != ParamEnd; ++Param) {
8916 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00008917 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8918 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008919 ClassOrEnumParam = true;
8920 break;
8921 }
8922 }
8923
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008924 if (!ClassOrEnumParam)
8925 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008926 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008927 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008928 }
8929
8930 // C++ [over.oper]p8:
8931 // An operator function cannot have default arguments (8.3.6),
8932 // except where explicitly stated below.
8933 //
Mike Stump1eb44332009-09-09 15:08:12 +00008934 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008935 // (C++ [over.call]p1).
8936 if (Op != OO_Call) {
8937 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8938 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00008939 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00008940 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00008941 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00008942 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008943 }
8944 }
8945
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008946 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8947 { false, false, false }
8948#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8949 , { Unary, Binary, MemberOnly }
8950#include "clang/Basic/OperatorKinds.def"
8951 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008952
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008953 bool CanBeUnaryOperator = OperatorUses[Op][0];
8954 bool CanBeBinaryOperator = OperatorUses[Op][1];
8955 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008956
8957 // C++ [over.oper]p8:
8958 // [...] Operator functions cannot have more or fewer parameters
8959 // than the number required for the corresponding operator, as
8960 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00008961 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008962 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008963 if (Op != OO_Call &&
8964 ((NumParams == 1 && !CanBeUnaryOperator) ||
8965 (NumParams == 2 && !CanBeBinaryOperator) ||
8966 (NumParams < 1) || (NumParams > 2))) {
8967 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00008968 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008969 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008970 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008971 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008972 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008973 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00008974 assert(CanBeBinaryOperator &&
8975 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00008976 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008977 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008978
Chris Lattner416e46f2008-11-21 07:57:12 +00008979 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008980 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008981 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00008982
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008983 // Overloaded operators other than operator() cannot be variadic.
8984 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00008985 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008986 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008987 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008988 }
8989
8990 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008991 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
8992 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008993 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008994 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008995 }
8996
8997 // C++ [over.inc]p1:
8998 // The user-defined function called operator++ implements the
8999 // prefix and postfix ++ operator. If this function is a member
9000 // function with no parameters, or a non-member function with one
9001 // parameter of class or enumeration type, it defines the prefix
9002 // increment operator ++ for objects of that type. If the function
9003 // is a member function with one parameter (which shall be of type
9004 // int) or a non-member function with two parameters (the second
9005 // of which shall be of type int), it defines the postfix
9006 // increment operator ++ for objects of that type.
9007 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9008 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9009 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009010 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009011 ParamIsInt = BT->getKind() == BuiltinType::Int;
9012
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009013 if (!ParamIsInt)
9014 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009015 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009016 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009017 }
9018
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009019 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009020}
Chris Lattner5a003a42008-12-17 07:09:26 +00009021
Sean Hunta6c058d2010-01-13 09:01:02 +00009022/// CheckLiteralOperatorDeclaration - Check whether the declaration
9023/// of this literal operator function is well-formed. If so, returns
9024/// false; otherwise, emits appropriate diagnostics and returns true.
9025bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9026 DeclContext *DC = FnDecl->getDeclContext();
9027 Decl::Kind Kind = DC->getDeclKind();
9028 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9029 Kind != Decl::LinkageSpec) {
9030 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9031 << FnDecl->getDeclName();
9032 return true;
9033 }
9034
9035 bool Valid = false;
9036
Sean Hunt216c2782010-04-07 23:11:06 +00009037 // template <char...> type operator "" name() is the only valid template
9038 // signature, and the only valid signature with no parameters.
9039 if (FnDecl->param_size() == 0) {
9040 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9041 // Must have only one template parameter
9042 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9043 if (Params->size() == 1) {
9044 NonTypeTemplateParmDecl *PmDecl =
9045 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009046
Sean Hunt216c2782010-04-07 23:11:06 +00009047 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009048 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9049 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9050 Valid = true;
9051 }
9052 }
9053 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009054 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009055 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9056
Sean Hunta6c058d2010-01-13 09:01:02 +00009057 QualType T = (*Param)->getType();
9058
Sean Hunt30019c02010-04-07 22:57:35 +00009059 // unsigned long long int, long double, and any character type are allowed
9060 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009061 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9062 Context.hasSameType(T, Context.LongDoubleTy) ||
9063 Context.hasSameType(T, Context.CharTy) ||
9064 Context.hasSameType(T, Context.WCharTy) ||
9065 Context.hasSameType(T, Context.Char16Ty) ||
9066 Context.hasSameType(T, Context.Char32Ty)) {
9067 if (++Param == FnDecl->param_end())
9068 Valid = true;
9069 goto FinishedParams;
9070 }
9071
Sean Hunt30019c02010-04-07 22:57:35 +00009072 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009073 const PointerType *PT = T->getAs<PointerType>();
9074 if (!PT)
9075 goto FinishedParams;
9076 T = PT->getPointeeType();
9077 if (!T.isConstQualified())
9078 goto FinishedParams;
9079 T = T.getUnqualifiedType();
9080
9081 // Move on to the second parameter;
9082 ++Param;
9083
9084 // If there is no second parameter, the first must be a const char *
9085 if (Param == FnDecl->param_end()) {
9086 if (Context.hasSameType(T, Context.CharTy))
9087 Valid = true;
9088 goto FinishedParams;
9089 }
9090
9091 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9092 // are allowed as the first parameter to a two-parameter function
9093 if (!(Context.hasSameType(T, Context.CharTy) ||
9094 Context.hasSameType(T, Context.WCharTy) ||
9095 Context.hasSameType(T, Context.Char16Ty) ||
9096 Context.hasSameType(T, Context.Char32Ty)))
9097 goto FinishedParams;
9098
9099 // The second and final parameter must be an std::size_t
9100 T = (*Param)->getType().getUnqualifiedType();
9101 if (Context.hasSameType(T, Context.getSizeType()) &&
9102 ++Param == FnDecl->param_end())
9103 Valid = true;
9104 }
9105
9106 // FIXME: This diagnostic is absolutely terrible.
9107FinishedParams:
9108 if (!Valid) {
9109 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9110 << FnDecl->getDeclName();
9111 return true;
9112 }
9113
Douglas Gregor1155c422011-08-30 22:40:35 +00009114 StringRef LiteralName
9115 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9116 if (LiteralName[0] != '_') {
9117 // C++0x [usrlit.suffix]p1:
9118 // Literal suffix identifiers that do not start with an underscore are
9119 // reserved for future standardization.
9120 bool IsHexFloat = true;
9121 if (LiteralName.size() > 1 &&
9122 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9123 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9124 if (!isdigit(LiteralName[I])) {
9125 IsHexFloat = false;
9126 break;
9127 }
9128 }
9129 }
9130
9131 if (IsHexFloat)
9132 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9133 << LiteralName;
9134 else
9135 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9136 }
9137
Sean Hunta6c058d2010-01-13 09:01:02 +00009138 return false;
9139}
9140
Douglas Gregor074149e2009-01-05 19:45:36 +00009141/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9142/// linkage specification, including the language and (if present)
9143/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9144/// the location of the language string literal, which is provided
9145/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9146/// the '{' brace. Otherwise, this linkage specification does not
9147/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009148Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9149 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009150 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009151 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009152 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009153 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009154 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009155 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009156 Language = LinkageSpecDecl::lang_cxx;
9157 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009158 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009159 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009160 }
Mike Stump1eb44332009-09-09 15:08:12 +00009161
Chris Lattnercc98eac2008-12-17 07:13:27 +00009162 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009163
Douglas Gregor074149e2009-01-05 19:45:36 +00009164 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009165 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009166 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009167 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009168 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009169}
9170
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009171/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009172/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9173/// valid, it's the position of the closing '}' brace in a linkage
9174/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009175Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009176 Decl *LinkageSpec,
9177 SourceLocation RBraceLoc) {
9178 if (LinkageSpec) {
9179 if (RBraceLoc.isValid()) {
9180 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9181 LSDecl->setRBraceLoc(RBraceLoc);
9182 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009183 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009184 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009185 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009186}
9187
Douglas Gregord308e622009-05-18 20:51:54 +00009188/// \brief Perform semantic analysis for the variable declaration that
9189/// occurs within a C++ catch clause, returning the newly-created
9190/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009191VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009192 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009193 SourceLocation StartLoc,
9194 SourceLocation Loc,
9195 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009196 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009197 QualType ExDeclType = TInfo->getType();
9198
Sebastian Redl4b07b292008-12-22 19:15:10 +00009199 // Arrays and functions decay.
9200 if (ExDeclType->isArrayType())
9201 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9202 else if (ExDeclType->isFunctionType())
9203 ExDeclType = Context.getPointerType(ExDeclType);
9204
9205 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9206 // The exception-declaration shall not denote a pointer or reference to an
9207 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009208 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009209 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009210 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009211 Invalid = true;
9212 }
Douglas Gregord308e622009-05-18 20:51:54 +00009213
Douglas Gregora2762912010-03-08 01:47:36 +00009214 // GCC allows catching pointers and references to incomplete types
9215 // as an extension; so do we, but we warn by default.
9216
Sebastian Redl4b07b292008-12-22 19:15:10 +00009217 QualType BaseType = ExDeclType;
9218 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009219 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009220 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009221 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009222 BaseType = Ptr->getPointeeType();
9223 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009224 DK = diag::ext_catch_incomplete_ptr;
9225 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009226 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009227 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009228 BaseType = Ref->getPointeeType();
9229 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009230 DK = diag::ext_catch_incomplete_ref;
9231 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009232 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009233 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009234 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9235 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009236 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009237
Mike Stump1eb44332009-09-09 15:08:12 +00009238 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009239 RequireNonAbstractType(Loc, ExDeclType,
9240 diag::err_abstract_type_in_decl,
9241 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009242 Invalid = true;
9243
John McCall5a180392010-07-24 00:37:23 +00009244 // Only the non-fragile NeXT runtime currently supports C++ catches
9245 // of ObjC types, and no runtime supports catching ObjC types by value.
9246 if (!Invalid && getLangOptions().ObjC1) {
9247 QualType T = ExDeclType;
9248 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9249 T = RT->getPointeeType();
9250
9251 if (T->isObjCObjectType()) {
9252 Diag(Loc, diag::err_objc_object_catch);
9253 Invalid = true;
9254 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009255 if (!getLangOptions().ObjCNonFragileABI)
9256 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009257 }
9258 }
9259
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009260 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9261 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009262 ExDecl->setExceptionVariable(true);
9263
Douglas Gregorc41b8782011-07-06 18:14:43 +00009264 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009265 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009266 // C++ [except.handle]p16:
9267 // The object declared in an exception-declaration or, if the
9268 // exception-declaration does not specify a name, a temporary (12.2) is
9269 // copy-initialized (8.5) from the exception object. [...]
9270 // The object is destroyed when the handler exits, after the destruction
9271 // of any automatic objects initialized within the handler.
9272 //
9273 // We just pretend to initialize the object with itself, then make sure
9274 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009275 QualType initType = ExDeclType;
9276
9277 InitializedEntity entity =
9278 InitializedEntity::InitializeVariable(ExDecl);
9279 InitializationKind initKind =
9280 InitializationKind::CreateCopy(Loc, SourceLocation());
9281
9282 Expr *opaqueValue =
9283 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9284 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9285 ExprResult result = sequence.Perform(*this, entity, initKind,
9286 MultiExprArg(&opaqueValue, 1));
9287 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009288 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009289 else {
9290 // If the constructor used was non-trivial, set this as the
9291 // "initializer".
9292 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9293 if (!construct->getConstructor()->isTrivial()) {
9294 Expr *init = MaybeCreateExprWithCleanups(construct);
9295 ExDecl->setInit(init);
9296 }
9297
9298 // And make sure it's destructable.
9299 FinalizeVarWithDestructor(ExDecl, recordType);
9300 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009301 }
9302 }
9303
Douglas Gregord308e622009-05-18 20:51:54 +00009304 if (Invalid)
9305 ExDecl->setInvalidDecl();
9306
9307 return ExDecl;
9308}
9309
9310/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9311/// handler.
John McCalld226f652010-08-21 09:40:31 +00009312Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009313 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009314 bool Invalid = D.isInvalidType();
9315
9316 // Check for unexpanded parameter packs.
9317 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9318 UPPC_ExceptionType)) {
9319 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9320 D.getIdentifierLoc());
9321 Invalid = true;
9322 }
9323
Sebastian Redl4b07b292008-12-22 19:15:10 +00009324 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009325 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009326 LookupOrdinaryName,
9327 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009328 // The scope should be freshly made just for us. There is just no way
9329 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009330 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009331 if (PrevDecl->isTemplateParameter()) {
9332 // Maybe we will complain about the shadowed template parameter.
9333 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009334 }
9335 }
9336
Chris Lattnereaaebc72009-04-25 08:06:05 +00009337 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009338 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9339 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009340 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009341 }
9342
Douglas Gregor83cb9422010-09-09 17:09:21 +00009343 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009344 D.getSourceRange().getBegin(),
9345 D.getIdentifierLoc(),
9346 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009347 if (Invalid)
9348 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009349
Sebastian Redl4b07b292008-12-22 19:15:10 +00009350 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009351 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009352 PushOnScopeChains(ExDecl, S);
9353 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009354 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009355
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009356 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009357 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009358}
Anders Carlssonfb311762009-03-14 00:25:26 +00009359
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009360Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009361 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009362 Expr *AssertMessageExpr_,
9363 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009364 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009365
Anders Carlssonc3082412009-03-14 00:33:21 +00009366 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9367 llvm::APSInt Value(32);
9368 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009369 Diag(StaticAssertLoc,
9370 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00009371 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009372 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00009373 }
Anders Carlssonfb311762009-03-14 00:25:26 +00009374
Anders Carlssonc3082412009-03-14 00:33:21 +00009375 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009376 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009377 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009378 }
9379 }
Mike Stump1eb44332009-09-09 15:08:12 +00009380
Douglas Gregor399ad972010-12-15 23:55:21 +00009381 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9382 return 0;
9383
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009384 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9385 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009386
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009387 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009388 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009389}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009390
Douglas Gregor1d869352010-04-07 16:53:43 +00009391/// \brief Perform semantic analysis of the given friend type declaration.
9392///
9393/// \returns A friend declaration that.
9394FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9395 TypeSourceInfo *TSInfo) {
9396 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9397
9398 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009399 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009400
Douglas Gregor06245bf2010-04-07 17:57:12 +00009401 if (!getLangOptions().CPlusPlus0x) {
9402 // C++03 [class.friend]p2:
9403 // An elaborated-type-specifier shall be used in a friend declaration
9404 // for a class.*
9405 //
9406 // * The class-key of the elaborated-type-specifier is required.
9407 if (!ActiveTemplateInstantiations.empty()) {
9408 // Do not complain about the form of friend template types during
9409 // template instantiation; we will already have complained when the
9410 // template was declared.
9411 } else if (!T->isElaboratedTypeSpecifier()) {
9412 // If we evaluated the type to a record type, suggest putting
9413 // a tag in front.
9414 if (const RecordType *RT = T->getAs<RecordType>()) {
9415 RecordDecl *RD = RT->getDecl();
9416
9417 std::string InsertionText = std::string(" ") + RD->getKindName();
9418
9419 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9420 << (unsigned) RD->getTagKind()
9421 << T
9422 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9423 InsertionText);
9424 } else {
9425 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9426 << T
9427 << SourceRange(FriendLoc, TypeRange.getEnd());
9428 }
9429 } else if (T->getAs<EnumType>()) {
9430 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009431 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009432 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009433 }
9434 }
9435
Douglas Gregor06245bf2010-04-07 17:57:12 +00009436 // C++0x [class.friend]p3:
9437 // If the type specifier in a friend declaration designates a (possibly
9438 // cv-qualified) class type, that class is declared as a friend; otherwise,
9439 // the friend declaration is ignored.
9440
9441 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9442 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009443
9444 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9445}
9446
John McCall9a34edb2010-10-19 01:40:49 +00009447/// Handle a friend tag declaration where the scope specifier was
9448/// templated.
9449Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9450 unsigned TagSpec, SourceLocation TagLoc,
9451 CXXScopeSpec &SS,
9452 IdentifierInfo *Name, SourceLocation NameLoc,
9453 AttributeList *Attr,
9454 MultiTemplateParamsArg TempParamLists) {
9455 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9456
9457 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009458 bool Invalid = false;
9459
9460 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009461 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009462 TempParamLists.get(),
9463 TempParamLists.size(),
9464 /*friend*/ true,
9465 isExplicitSpecialization,
9466 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009467 if (TemplateParams->size() > 0) {
9468 // This is a declaration of a class template.
9469 if (Invalid)
9470 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009471
Eric Christopher4110e132011-07-21 05:34:24 +00009472 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9473 SS, Name, NameLoc, Attr,
9474 TemplateParams, AS_public,
Douglas Gregor8d267c52011-09-09 02:06:17 +00009475 /*IsModulePrivate=*/false,
Eric Christopher4110e132011-07-21 05:34:24 +00009476 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009477 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009478 } else {
9479 // The "template<>" header is extraneous.
9480 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9481 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9482 isExplicitSpecialization = true;
9483 }
9484 }
9485
9486 if (Invalid) return 0;
9487
9488 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9489
9490 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009491 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009492 if (TempParamLists.get()[I]->size()) {
9493 isAllExplicitSpecializations = false;
9494 break;
9495 }
9496 }
9497
9498 // FIXME: don't ignore attributes.
9499
9500 // If it's explicit specializations all the way down, just forget
9501 // about the template header and build an appropriate non-templated
9502 // friend. TODO: for source fidelity, remember the headers.
9503 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00009504 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009505 ElaboratedTypeKeyword Keyword
9506 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009507 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009508 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009509 if (T.isNull())
9510 return 0;
9511
9512 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9513 if (isa<DependentNameType>(T)) {
9514 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9515 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009516 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009517 TL.setNameLoc(NameLoc);
9518 } else {
9519 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9520 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009521 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009522 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9523 }
9524
9525 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9526 TSI, FriendLoc);
9527 Friend->setAccess(AS_public);
9528 CurContext->addDecl(Friend);
9529 return Friend;
9530 }
9531
9532 // Handle the case of a templated-scope friend class. e.g.
9533 // template <class T> class A<T>::B;
9534 // FIXME: we don't support these right now.
9535 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9536 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9537 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9538 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9539 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009540 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009541 TL.setNameLoc(NameLoc);
9542
9543 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9544 TSI, FriendLoc);
9545 Friend->setAccess(AS_public);
9546 Friend->setUnsupportedFriend(true);
9547 CurContext->addDecl(Friend);
9548 return Friend;
9549}
9550
9551
John McCalldd4a3b02009-09-16 22:47:08 +00009552/// Handle a friend type declaration. This works in tandem with
9553/// ActOnTag.
9554///
9555/// Notes on friend class templates:
9556///
9557/// We generally treat friend class declarations as if they were
9558/// declaring a class. So, for example, the elaborated type specifier
9559/// in a friend declaration is required to obey the restrictions of a
9560/// class-head (i.e. no typedefs in the scope chain), template
9561/// parameters are required to match up with simple template-ids, &c.
9562/// However, unlike when declaring a template specialization, it's
9563/// okay to refer to a template specialization without an empty
9564/// template parameter declaration, e.g.
9565/// friend class A<T>::B<unsigned>;
9566/// We permit this as a special case; if there are any template
9567/// parameters present at all, require proper matching, i.e.
9568/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009569Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009570 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009571 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009572
9573 assert(DS.isFriendSpecified());
9574 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9575
John McCalldd4a3b02009-09-16 22:47:08 +00009576 // Try to convert the decl specifier to a type. This works for
9577 // friend templates because ActOnTag never produces a ClassTemplateDecl
9578 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009579 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009580 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9581 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009582 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009583 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009584
Douglas Gregor6ccab972010-12-16 01:14:37 +00009585 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9586 return 0;
9587
John McCalldd4a3b02009-09-16 22:47:08 +00009588 // This is definitely an error in C++98. It's probably meant to
9589 // be forbidden in C++0x, too, but the specification is just
9590 // poorly written.
9591 //
9592 // The problem is with declarations like the following:
9593 // template <T> friend A<T>::foo;
9594 // where deciding whether a class C is a friend or not now hinges
9595 // on whether there exists an instantiation of A that causes
9596 // 'foo' to equal C. There are restrictions on class-heads
9597 // (which we declare (by fiat) elaborated friend declarations to
9598 // be) that makes this tractable.
9599 //
9600 // FIXME: handle "template <> friend class A<T>;", which
9601 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009602 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009603 Diag(Loc, diag::err_tagless_friend_type_template)
9604 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009605 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009606 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009607
John McCall02cace72009-08-28 07:59:38 +00009608 // C++98 [class.friend]p1: A friend of a class is a function
9609 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009610 // This is fixed in DR77, which just barely didn't make the C++03
9611 // deadline. It's also a very silly restriction that seriously
9612 // affects inner classes and which nobody else seems to implement;
9613 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009614 //
9615 // But note that we could warn about it: it's always useless to
9616 // friend one of your own members (it's not, however, worthless to
9617 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009618
John McCalldd4a3b02009-09-16 22:47:08 +00009619 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009620 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009621 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009622 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009623 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009624 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009625 DS.getFriendSpecLoc());
9626 else
Douglas Gregor1d869352010-04-07 16:53:43 +00009627 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9628
9629 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009630 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009631
John McCalldd4a3b02009-09-16 22:47:08 +00009632 D->setAccess(AS_public);
9633 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009634
John McCalld226f652010-08-21 09:40:31 +00009635 return D;
John McCall02cace72009-08-28 07:59:38 +00009636}
9637
John McCall337ec3d2010-10-12 23:13:28 +00009638Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9639 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009640 const DeclSpec &DS = D.getDeclSpec();
9641
9642 assert(DS.isFriendSpecified());
9643 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9644
9645 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009646 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9647 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00009648
9649 // C++ [class.friend]p1
9650 // A friend of a class is a function or class....
9651 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009652 // It *doesn't* see through dependent types, which is correct
9653 // according to [temp.arg.type]p3:
9654 // If a declaration acquires a function type through a
9655 // type dependent on a template-parameter and this causes
9656 // a declaration that does not use the syntactic form of a
9657 // function declarator to have a function type, the program
9658 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00009659 if (!T->isFunctionType()) {
9660 Diag(Loc, diag::err_unexpected_friend);
9661
9662 // It might be worthwhile to try to recover by creating an
9663 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009664 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009665 }
9666
9667 // C++ [namespace.memdef]p3
9668 // - If a friend declaration in a non-local class first declares a
9669 // class or function, the friend class or function is a member
9670 // of the innermost enclosing namespace.
9671 // - The name of the friend is not found by simple name lookup
9672 // until a matching declaration is provided in that namespace
9673 // scope (either before or after the class declaration granting
9674 // friendship).
9675 // - If a friend function is called, its name may be found by the
9676 // name lookup that considers functions from namespaces and
9677 // classes associated with the types of the function arguments.
9678 // - When looking for a prior declaration of a class or a function
9679 // declared as a friend, scopes outside the innermost enclosing
9680 // namespace scope are not considered.
9681
John McCall337ec3d2010-10-12 23:13:28 +00009682 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009683 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9684 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009685 assert(Name);
9686
Douglas Gregor6ccab972010-12-16 01:14:37 +00009687 // Check for unexpanded parameter packs.
9688 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9689 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9690 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9691 return 0;
9692
John McCall67d1a672009-08-06 02:15:43 +00009693 // The context we found the declaration in, or in which we should
9694 // create the declaration.
9695 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009696 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009697 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009698 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009699
John McCall337ec3d2010-10-12 23:13:28 +00009700 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009701
John McCall337ec3d2010-10-12 23:13:28 +00009702 // There are four cases here.
9703 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009704 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009705 // there as appropriate.
9706 // Recover from invalid scope qualifiers as if they just weren't there.
9707 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009708 // C++0x [namespace.memdef]p3:
9709 // If the name in a friend declaration is neither qualified nor
9710 // a template-id and the declaration is a function or an
9711 // elaborated-type-specifier, the lookup to determine whether
9712 // the entity has been previously declared shall not consider
9713 // any scopes outside the innermost enclosing namespace.
9714 // C++0x [class.friend]p11:
9715 // If a friend declaration appears in a local class and the name
9716 // specified is an unqualified name, a prior declaration is
9717 // looked up without considering scopes that are outside the
9718 // innermost enclosing non-class scope. For a friend function
9719 // declaration, if there is no prior declaration, the program is
9720 // ill-formed.
9721 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009722 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009723
John McCall29ae6e52010-10-13 05:45:15 +00009724 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009725 DC = CurContext;
9726 while (true) {
9727 // Skip class contexts. If someone can cite chapter and verse
9728 // for this behavior, that would be nice --- it's what GCC and
9729 // EDG do, and it seems like a reasonable intent, but the spec
9730 // really only says that checks for unqualified existing
9731 // declarations should stop at the nearest enclosing namespace,
9732 // not that they should only consider the nearest enclosing
9733 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00009734 while (DC->isRecord())
9735 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00009736
John McCall68263142009-11-18 22:49:29 +00009737 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00009738
9739 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00009740 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00009741 break;
John McCall29ae6e52010-10-13 05:45:15 +00009742
John McCall8a407372010-10-14 22:22:28 +00009743 if (isTemplateId) {
9744 if (isa<TranslationUnitDecl>(DC)) break;
9745 } else {
9746 if (DC->isFileContext()) break;
9747 }
John McCall67d1a672009-08-06 02:15:43 +00009748 DC = DC->getParent();
9749 }
9750
9751 // C++ [class.friend]p1: A friend of a class is a function or
9752 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00009753 // C++0x changes this for both friend types and functions.
9754 // Most C++ 98 compilers do seem to give an error here, so
9755 // we do, too.
John McCall68263142009-11-18 22:49:29 +00009756 if (!Previous.empty() && DC->Equals(CurContext)
9757 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00009758 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00009759
John McCall380aaa42010-10-13 06:22:15 +00009760 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00009761
John McCall337ec3d2010-10-12 23:13:28 +00009762 // - There's a non-dependent scope specifier, in which case we
9763 // compute it and do a previous lookup there for a function
9764 // or function template.
9765 } else if (!SS.getScopeRep()->isDependent()) {
9766 DC = computeDeclContext(SS);
9767 if (!DC) return 0;
9768
9769 if (RequireCompleteDeclContext(SS, DC)) return 0;
9770
9771 LookupQualifiedName(Previous, DC);
9772
9773 // Ignore things found implicitly in the wrong scope.
9774 // TODO: better diagnostics for this case. Suggesting the right
9775 // qualified scope would be nice...
9776 LookupResult::Filter F = Previous.makeFilter();
9777 while (F.hasNext()) {
9778 NamedDecl *D = F.next();
9779 if (!DC->InEnclosingNamespaceSetOf(
9780 D->getDeclContext()->getRedeclContext()))
9781 F.erase();
9782 }
9783 F.done();
9784
9785 if (Previous.empty()) {
9786 D.setInvalidType();
9787 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9788 return 0;
9789 }
9790
9791 // C++ [class.friend]p1: A friend of a class is a function or
9792 // class that is not a member of the class . . .
9793 if (DC->Equals(CurContext))
9794 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9795
9796 // - There's a scope specifier that does not match any template
9797 // parameter lists, in which case we use some arbitrary context,
9798 // create a method or method template, and wait for instantiation.
9799 // - There's a scope specifier that does match some template
9800 // parameter lists, which we don't handle right now.
9801 } else {
9802 DC = CurContext;
9803 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00009804 }
9805
John McCall29ae6e52010-10-13 05:45:15 +00009806 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00009807 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009808 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9809 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9810 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00009811 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009812 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9813 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00009814 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009815 }
John McCall67d1a672009-08-06 02:15:43 +00009816 }
9817
Douglas Gregor182ddf02009-09-28 00:08:27 +00009818 bool Redeclaration = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009819 bool AddToScope = true;
John McCall380aaa42010-10-13 06:22:15 +00009820 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00009821 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00009822 IsDefinition,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009823 Redeclaration, AddToScope);
John McCalld226f652010-08-21 09:40:31 +00009824 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00009825
Douglas Gregor182ddf02009-09-28 00:08:27 +00009826 assert(ND->getDeclContext() == DC);
9827 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00009828
John McCallab88d972009-08-31 22:39:49 +00009829 // Add the function declaration to the appropriate lookup tables,
9830 // adjusting the redeclarations list as necessary. We don't
9831 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00009832 //
John McCallab88d972009-08-31 22:39:49 +00009833 // Also update the scope-based lookup if the target context's
9834 // lookup context is in lexical scope.
9835 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009836 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00009837 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009838 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00009839 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009840 }
John McCall02cace72009-08-28 07:59:38 +00009841
9842 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00009843 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00009844 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00009845 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00009846 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00009847
John McCall337ec3d2010-10-12 23:13:28 +00009848 if (ND->isInvalidDecl())
9849 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00009850 else {
9851 FunctionDecl *FD;
9852 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9853 FD = FTD->getTemplatedDecl();
9854 else
9855 FD = cast<FunctionDecl>(ND);
9856
9857 // Mark templated-scope function declarations as unsupported.
9858 if (FD->getNumTemplateParameterLists())
9859 FrD->setUnsupportedFriend(true);
9860 }
John McCall337ec3d2010-10-12 23:13:28 +00009861
John McCalld226f652010-08-21 09:40:31 +00009862 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00009863}
9864
John McCalld226f652010-08-21 09:40:31 +00009865void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9866 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00009867
Sebastian Redl50de12f2009-03-24 22:27:57 +00009868 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9869 if (!Fn) {
9870 Diag(DelLoc, diag::err_deleted_non_function);
9871 return;
9872 }
9873 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9874 Diag(DelLoc, diag::err_deleted_decl_not_first);
9875 Diag(Prev->getLocation(), diag::note_previous_declaration);
9876 // If the declaration wasn't the first, we delete the function anyway for
9877 // recovery.
9878 }
Sean Hunt10620eb2011-05-06 20:44:56 +00009879 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00009880}
Sebastian Redl13e88542009-04-27 21:33:24 +00009881
Sean Hunte4246a62011-05-12 06:15:49 +00009882void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9883 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9884
9885 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00009886 if (MD->getParent()->isDependentType()) {
9887 MD->setDefaulted();
9888 MD->setExplicitlyDefaulted();
9889 return;
9890 }
9891
Sean Hunte4246a62011-05-12 06:15:49 +00009892 CXXSpecialMember Member = getSpecialMember(MD);
9893 if (Member == CXXInvalid) {
9894 Diag(DefaultLoc, diag::err_default_special_members);
9895 return;
9896 }
9897
9898 MD->setDefaulted();
9899 MD->setExplicitlyDefaulted();
9900
Sean Huntcd10dec2011-05-23 23:14:04 +00009901 // If this definition appears within the record, do the checking when
9902 // the record is complete.
9903 const FunctionDecl *Primary = MD;
9904 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9905 // Find the uninstantiated declaration that actually had the '= default'
9906 // on it.
9907 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9908
9909 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00009910 return;
9911
9912 switch (Member) {
9913 case CXXDefaultConstructor: {
9914 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9915 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009916 if (!CD->isInvalidDecl())
9917 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9918 break;
9919 }
9920
9921 case CXXCopyConstructor: {
9922 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9923 CheckExplicitlyDefaultedCopyConstructor(CD);
9924 if (!CD->isInvalidDecl())
9925 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00009926 break;
9927 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00009928
Sean Hunt2b188082011-05-14 05:23:28 +00009929 case CXXCopyAssignment: {
9930 CheckExplicitlyDefaultedCopyAssignment(MD);
9931 if (!MD->isInvalidDecl())
9932 DefineImplicitCopyAssignment(DefaultLoc, MD);
9933 break;
9934 }
9935
Sean Huntcb45a0f2011-05-12 22:46:25 +00009936 case CXXDestructor: {
9937 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9938 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009939 if (!DD->isInvalidDecl())
9940 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009941 break;
9942 }
9943
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009944 case CXXMoveConstructor: {
9945 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9946 CheckExplicitlyDefaultedMoveConstructor(CD);
9947 if (!CD->isInvalidDecl())
9948 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +00009949 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009950 }
Sean Hunt82713172011-05-25 23:16:36 +00009951
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009952 case CXXMoveAssignment: {
9953 CheckExplicitlyDefaultedMoveAssignment(MD);
9954 if (!MD->isInvalidDecl())
9955 DefineImplicitMoveAssignment(DefaultLoc, MD);
9956 break;
9957 }
9958
9959 case CXXInvalid:
9960 assert(false && "Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +00009961 break;
9962 }
9963 } else {
9964 Diag(DefaultLoc, diag::err_default_special_members);
9965 }
9966}
9967
Sebastian Redl13e88542009-04-27 21:33:24 +00009968static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00009969 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00009970 Stmt *SubStmt = *CI;
9971 if (!SubStmt)
9972 continue;
9973 if (isa<ReturnStmt>(SubStmt))
9974 Self.Diag(SubStmt->getSourceRange().getBegin(),
9975 diag::err_return_in_constructor_handler);
9976 if (!isa<Expr>(SubStmt))
9977 SearchForReturnInStmt(Self, SubStmt);
9978 }
9979}
9980
9981void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9982 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9983 CXXCatchStmt *Handler = TryBlock->getHandler(I);
9984 SearchForReturnInStmt(*this, Handler);
9985 }
9986}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009987
Mike Stump1eb44332009-09-09 15:08:12 +00009988bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009989 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00009990 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
9991 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009992
Chandler Carruth73857792010-02-15 11:53:20 +00009993 if (Context.hasSameType(NewTy, OldTy) ||
9994 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009995 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00009996
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009997 // Check if the return types are covariant
9998 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00009999
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010000 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010001 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10002 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010003 NewClassTy = NewPT->getPointeeType();
10004 OldClassTy = OldPT->getPointeeType();
10005 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010006 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10007 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10008 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10009 NewClassTy = NewRT->getPointeeType();
10010 OldClassTy = OldRT->getPointeeType();
10011 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010012 }
10013 }
Mike Stump1eb44332009-09-09 15:08:12 +000010014
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010015 // The return types aren't either both pointers or references to a class type.
10016 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010017 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010018 diag::err_different_return_type_for_overriding_virtual_function)
10019 << New->getDeclName() << NewTy << OldTy;
10020 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010021
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010022 return true;
10023 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010024
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010025 // C++ [class.virtual]p6:
10026 // If the return type of D::f differs from the return type of B::f, the
10027 // class type in the return type of D::f shall be complete at the point of
10028 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010029 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10030 if (!RT->isBeingDefined() &&
10031 RequireCompleteType(New->getLocation(), NewClassTy,
10032 PDiag(diag::err_covariant_return_incomplete)
10033 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010034 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010035 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010036
Douglas Gregora4923eb2009-11-16 21:35:15 +000010037 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010038 // Check if the new class derives from the old class.
10039 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10040 Diag(New->getLocation(),
10041 diag::err_covariant_return_not_derived)
10042 << New->getDeclName() << NewTy << OldTy;
10043 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10044 return true;
10045 }
Mike Stump1eb44332009-09-09 15:08:12 +000010046
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010047 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010048 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010049 diag::err_covariant_return_inaccessible_base,
10050 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10051 // FIXME: Should this point to the return type?
10052 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010053 // FIXME: this note won't trigger for delayed access control
10054 // diagnostics, and it's impossible to get an undelayed error
10055 // here from access control during the original parse because
10056 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010057 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10058 return true;
10059 }
10060 }
Mike Stump1eb44332009-09-09 15:08:12 +000010061
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010062 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010063 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010064 Diag(New->getLocation(),
10065 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010066 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010067 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10068 return true;
10069 };
Mike Stump1eb44332009-09-09 15:08:12 +000010070
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010071
10072 // The new class type must have the same or less qualifiers as the old type.
10073 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10074 Diag(New->getLocation(),
10075 diag::err_covariant_return_type_class_type_more_qualified)
10076 << New->getDeclName() << NewTy << OldTy;
10077 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10078 return true;
10079 };
Mike Stump1eb44332009-09-09 15:08:12 +000010080
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010081 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010082}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010083
Douglas Gregor4ba31362009-12-01 17:24:26 +000010084/// \brief Mark the given method pure.
10085///
10086/// \param Method the method to be marked pure.
10087///
10088/// \param InitRange the source range that covers the "0" initializer.
10089bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010090 SourceLocation EndLoc = InitRange.getEnd();
10091 if (EndLoc.isValid())
10092 Method->setRangeEnd(EndLoc);
10093
Douglas Gregor4ba31362009-12-01 17:24:26 +000010094 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10095 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010096 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010097 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010098
10099 if (!Method->isInvalidDecl())
10100 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10101 << Method->getDeclName() << InitRange;
10102 return true;
10103}
10104
John McCall731ad842009-12-19 09:28:58 +000010105/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10106/// an initializer for the out-of-line declaration 'Dcl'. The scope
10107/// is a fresh scope pushed for just this purpose.
10108///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010109/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10110/// static data member of class X, names should be looked up in the scope of
10111/// class X.
John McCalld226f652010-08-21 09:40:31 +000010112void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010113 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010114 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010115
John McCall731ad842009-12-19 09:28:58 +000010116 // We should only get called for declarations with scope specifiers, like:
10117 // int foo::bar;
10118 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010119 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010120}
10121
10122/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010123/// initializer for the out-of-line declaration 'D'.
10124void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010125 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010126 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010127
John McCall731ad842009-12-19 09:28:58 +000010128 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010129 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010130}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010131
10132/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10133/// C++ if/switch/while/for statement.
10134/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010135DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010136 // C++ 6.4p2:
10137 // The declarator shall not specify a function or an array.
10138 // The type-specifier-seq shall not contain typedef and shall not declare a
10139 // new class or enumeration.
10140 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10141 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010142
10143 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010144 if (!Dcl)
10145 return true;
10146
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010147 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10148 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010149 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010150 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010151 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010152
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010153 return Dcl;
10154}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010155
Douglas Gregordfe65432011-07-28 19:11:31 +000010156void Sema::LoadExternalVTableUses() {
10157 if (!ExternalSource)
10158 return;
10159
10160 SmallVector<ExternalVTableUse, 4> VTables;
10161 ExternalSource->ReadUsedVTables(VTables);
10162 SmallVector<VTableUse, 4> NewUses;
10163 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10164 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10165 = VTablesUsed.find(VTables[I].Record);
10166 // Even if a definition wasn't required before, it may be required now.
10167 if (Pos != VTablesUsed.end()) {
10168 if (!Pos->second && VTables[I].DefinitionRequired)
10169 Pos->second = true;
10170 continue;
10171 }
10172
10173 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10174 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10175 }
10176
10177 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10178}
10179
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010180void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10181 bool DefinitionRequired) {
10182 // Ignore any vtable uses in unevaluated operands or for classes that do
10183 // not have a vtable.
10184 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10185 CurContext->isDependentContext() ||
10186 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010187 return;
10188
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010189 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010190 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010191 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10192 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10193 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10194 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010195 // If we already had an entry, check to see if we are promoting this vtable
10196 // to required a definition. If so, we need to reappend to the VTableUses
10197 // list, since we may have already processed the first entry.
10198 if (DefinitionRequired && !Pos.first->second) {
10199 Pos.first->second = true;
10200 } else {
10201 // Otherwise, we can early exit.
10202 return;
10203 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010204 }
10205
10206 // Local classes need to have their virtual members marked
10207 // immediately. For all other classes, we mark their virtual members
10208 // at the end of the translation unit.
10209 if (Class->isLocalClass())
10210 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010211 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010212 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010213}
10214
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010215bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010216 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010217 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010218 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010219
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010220 // Note: The VTableUses vector could grow as a result of marking
10221 // the members of a class as "used", so we check the size each
10222 // time through the loop and prefer indices (with are stable) to
10223 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010224 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010225 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010226 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010227 if (!Class)
10228 continue;
10229
10230 SourceLocation Loc = VTableUses[I].second;
10231
10232 // If this class has a key function, but that key function is
10233 // defined in another translation unit, we don't need to emit the
10234 // vtable even though we're using it.
10235 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010236 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010237 switch (KeyFunction->getTemplateSpecializationKind()) {
10238 case TSK_Undeclared:
10239 case TSK_ExplicitSpecialization:
10240 case TSK_ExplicitInstantiationDeclaration:
10241 // The key function is in another translation unit.
10242 continue;
10243
10244 case TSK_ExplicitInstantiationDefinition:
10245 case TSK_ImplicitInstantiation:
10246 // We will be instantiating the key function.
10247 break;
10248 }
10249 } else if (!KeyFunction) {
10250 // If we have a class with no key function that is the subject
10251 // of an explicit instantiation declaration, suppress the
10252 // vtable; it will live with the explicit instantiation
10253 // definition.
10254 bool IsExplicitInstantiationDeclaration
10255 = Class->getTemplateSpecializationKind()
10256 == TSK_ExplicitInstantiationDeclaration;
10257 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10258 REnd = Class->redecls_end();
10259 R != REnd; ++R) {
10260 TemplateSpecializationKind TSK
10261 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10262 if (TSK == TSK_ExplicitInstantiationDeclaration)
10263 IsExplicitInstantiationDeclaration = true;
10264 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10265 IsExplicitInstantiationDeclaration = false;
10266 break;
10267 }
10268 }
10269
10270 if (IsExplicitInstantiationDeclaration)
10271 continue;
10272 }
10273
10274 // Mark all of the virtual members of this class as referenced, so
10275 // that we can build a vtable. Then, tell the AST consumer that a
10276 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010277 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010278 MarkVirtualMembersReferenced(Loc, Class);
10279 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10280 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10281
10282 // Optionally warn if we're emitting a weak vtable.
10283 if (Class->getLinkage() == ExternalLinkage &&
10284 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010285 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010286 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10287 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010288 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010289 VTableUses.clear();
10290
Douglas Gregor78844032011-04-22 22:25:37 +000010291 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010292}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010293
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010294void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10295 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010296 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10297 e = RD->method_end(); i != e; ++i) {
10298 CXXMethodDecl *MD = *i;
10299
10300 // C++ [basic.def.odr]p2:
10301 // [...] A virtual member function is used if it is not pure. [...]
10302 if (MD->isVirtual() && !MD->isPure())
10303 MarkDeclarationReferenced(Loc, MD);
10304 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010305
10306 // Only classes that have virtual bases need a VTT.
10307 if (RD->getNumVBases() == 0)
10308 return;
10309
10310 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10311 e = RD->bases_end(); i != e; ++i) {
10312 const CXXRecordDecl *Base =
10313 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010314 if (Base->getNumVBases() == 0)
10315 continue;
10316 MarkVirtualMembersReferenced(Loc, Base);
10317 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010318}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010319
10320/// SetIvarInitializers - This routine builds initialization ASTs for the
10321/// Objective-C implementation whose ivars need be initialized.
10322void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10323 if (!getLangOptions().CPlusPlus)
10324 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010325 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010326 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010327 CollectIvarsToConstructOrDestruct(OID, ivars);
10328 if (ivars.empty())
10329 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010330 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010331 for (unsigned i = 0; i < ivars.size(); i++) {
10332 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010333 if (Field->isInvalidDecl())
10334 continue;
10335
Sean Huntcbb67482011-01-08 20:30:50 +000010336 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010337 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10338 InitializationKind InitKind =
10339 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10340
10341 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010342 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010343 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010344 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010345 // Note, MemberInit could actually come back empty if no initialization
10346 // is required (e.g., because it would call a trivial default constructor)
10347 if (!MemberInit.get() || MemberInit.isInvalid())
10348 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010349
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010350 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010351 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10352 SourceLocation(),
10353 MemberInit.takeAs<Expr>(),
10354 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010355 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010356
10357 // Be sure that the destructor is accessible and is marked as referenced.
10358 if (const RecordType *RecordTy
10359 = Context.getBaseElementType(Field->getType())
10360 ->getAs<RecordType>()) {
10361 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010362 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010363 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10364 CheckDestructorAccess(Field->getLocation(), Destructor,
10365 PDiag(diag::err_access_dtor_ivar)
10366 << Context.getBaseElementType(Field->getType()));
10367 }
10368 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010369 }
10370 ObjCImplementation->setIvarInitializers(Context,
10371 AllToInit.data(), AllToInit.size());
10372 }
10373}
Sean Huntfe57eef2011-05-04 05:57:24 +000010374
Sean Huntebcbe1d2011-05-04 23:29:54 +000010375static
10376void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10377 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10378 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10379 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10380 Sema &S) {
10381 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10382 CE = Current.end();
10383 if (Ctor->isInvalidDecl())
10384 return;
10385
10386 const FunctionDecl *FNTarget = 0;
10387 CXXConstructorDecl *Target;
10388
10389 // We ignore the result here since if we don't have a body, Target will be
10390 // null below.
10391 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10392 Target
10393= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10394
10395 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10396 // Avoid dereferencing a null pointer here.
10397 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10398
10399 if (!Current.insert(Canonical))
10400 return;
10401
10402 // We know that beyond here, we aren't chaining into a cycle.
10403 if (!Target || !Target->isDelegatingConstructor() ||
10404 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10405 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10406 Valid.insert(*CI);
10407 Current.clear();
10408 // We've hit a cycle.
10409 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10410 Current.count(TCanonical)) {
10411 // If we haven't diagnosed this cycle yet, do so now.
10412 if (!Invalid.count(TCanonical)) {
10413 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010414 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010415 << Ctor;
10416
10417 // Don't add a note for a function delegating directo to itself.
10418 if (TCanonical != Canonical)
10419 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10420
10421 CXXConstructorDecl *C = Target;
10422 while (C->getCanonicalDecl() != Canonical) {
10423 (void)C->getTargetConstructor()->hasBody(FNTarget);
10424 assert(FNTarget && "Ctor cycle through bodiless function");
10425
10426 C
10427 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10428 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10429 }
10430 }
10431
10432 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10433 Invalid.insert(*CI);
10434 Current.clear();
10435 } else {
10436 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10437 }
10438}
10439
10440
Sean Huntfe57eef2011-05-04 05:57:24 +000010441void Sema::CheckDelegatingCtorCycles() {
10442 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10443
Sean Huntebcbe1d2011-05-04 23:29:54 +000010444 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10445 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010446
Douglas Gregor0129b562011-07-27 21:57:17 +000010447 for (DelegatingCtorDeclsType::iterator
10448 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010449 E = DelegatingCtorDecls.end();
10450 I != E; ++I) {
10451 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010452 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010453
10454 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10455 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010456}