blob: 9f146e9254c6da72bc342e8c7ff693ec8ef72641 [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");
Sean Hunt001cad92011-05-10 00:49:42 +0000116 // If we have an MSAny spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny)
118 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.
126 if (EST == EST_MSAny || EST == EST_None) {
127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
132 // If this function has a basic noexcept, it doesn't affect the outcome.
133 if (EST == EST_BasicNoexcept)
134 return;
135
136 // If we have a throw-all spec at this point, ignore the function.
137 if (ComputedEST == EST_None)
138 return;
139
140 // If we're still at noexcept(true) and there's a nothrow() callee,
141 // change to that specification.
142 if (EST == EST_DynamicNone) {
143 if (ComputedEST == EST_BasicNoexcept)
144 ComputedEST = EST_DynamicNone;
145 return;
146 }
147
148 // Check out noexcept specs.
149 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000150 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000151 assert(NR != FunctionProtoType::NR_NoNoexcept &&
152 "Must have noexcept result for EST_ComputedNoexcept.");
153 assert(NR != FunctionProtoType::NR_Dependent &&
154 "Should not generate implicit declarations for dependent cases, "
155 "and don't know how to handle them anyway.");
156
157 // noexcept(false) -> no spec on the new function
158 if (NR == FunctionProtoType::NR_Throw) {
159 ClearExceptions();
160 ComputedEST = EST_None;
161 }
162 // noexcept(true) won't change anything either.
163 return;
164 }
165
166 assert(EST == EST_Dynamic && "EST case not considered earlier.");
167 assert(ComputedEST != EST_None &&
168 "Shouldn't collect exceptions when throw-all is guaranteed.");
169 ComputedEST = EST_Dynamic;
170 // Record the exceptions in this function's exception specification.
171 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
172 EEnd = Proto->exception_end();
173 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000174 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000175 Exceptions.push_back(*E);
176}
177
Anders Carlssoned961f92009-08-25 02:29:20 +0000178bool
John McCall9ae2f072010-08-23 23:25:46 +0000179Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000180 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000181 if (RequireCompleteType(Param->getLocation(), Param->getType(),
182 diag::err_typecheck_decl_incomplete_type)) {
183 Param->setInvalidDecl();
184 return true;
185 }
186
Anders Carlssoned961f92009-08-25 02:29:20 +0000187 // C++ [dcl.fct.default]p5
188 // A default argument expression is implicitly converted (clause
189 // 4) to the parameter type. The default argument expression has
190 // the same semantic constraints as the initializer expression in
191 // a declaration of a variable of the parameter type, using the
192 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000193 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
194 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000195 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
196 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000197 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000198 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000199 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000200 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000201 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000202 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000203
John McCallb4eb64d2010-10-08 02:01:28 +0000204 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000205 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Anders Carlssoned961f92009-08-25 02:29:20 +0000207 // Okay: add the default argument to the parameter
208 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000210 // We have already instantiated this parameter; provide each of the
211 // instantiations with the uninstantiated default argument.
212 UnparsedDefaultArgInstantiationsMap::iterator InstPos
213 = UnparsedDefaultArgInstantiations.find(Param);
214 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
215 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
216 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
217
218 // We're done tracking this parameter's instantiations.
219 UnparsedDefaultArgInstantiations.erase(InstPos);
220 }
221
Anders Carlsson9351c172009-08-25 03:18:48 +0000222 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000223}
224
Chris Lattner8123a952008-04-10 02:22:51 +0000225/// ActOnParamDefaultArgument - Check whether the default argument
226/// provided for a function parameter is well-formed. If so, attach it
227/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000228void
John McCalld226f652010-08-21 09:40:31 +0000229Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000230 Expr *DefaultArg) {
231 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000232 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
John McCalld226f652010-08-21 09:40:31 +0000234 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000235 UnparsedDefaultArgLocs.erase(Param);
236
Chris Lattner3d1cee32008-04-08 05:04:30 +0000237 // Default arguments are only permitted in C++
238 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000239 Diag(EqualLoc, diag::err_param_default_argument)
240 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000241 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000242 return;
243 }
244
Douglas Gregor6f526752010-12-16 08:48:57 +0000245 // Check for unexpanded parameter packs.
246 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
247 Param->setInvalidDecl();
248 return;
249 }
250
Anders Carlsson66e30672009-08-25 01:02:06 +0000251 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000252 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
253 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000254 Param->setInvalidDecl();
255 return;
256 }
Mike Stump1eb44332009-09-09 15:08:12 +0000257
John McCall9ae2f072010-08-23 23:25:46 +0000258 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000259}
260
Douglas Gregor61366e92008-12-24 00:01:03 +0000261/// ActOnParamUnparsedDefaultArgument - We've seen a default
262/// argument for a function parameter, but we can't parse it yet
263/// because we're inside a class definition. Note that this default
264/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000265void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000266 SourceLocation EqualLoc,
267 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000268 if (!param)
269 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000270
John McCalld226f652010-08-21 09:40:31 +0000271 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000272 if (Param)
273 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Anders Carlsson5e300d12009-06-12 16:51:40 +0000275 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000276}
277
Douglas Gregor72b505b2008-12-16 21:30:33 +0000278/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
279/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000280void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000281 if (!param)
282 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
John McCalld226f652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Anders Carlsson5e300d12009-06-12 16:51:40 +0000288 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000289}
290
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000291/// CheckExtraCXXDefaultArguments - Check for any extra default
292/// arguments in the declarator, which is not a function declaration
293/// or definition and therefore is not permitted to have default
294/// arguments. This routine should be invoked for every declarator
295/// that is not a function declaration or definition.
296void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
297 // C++ [dcl.fct.default]p3
298 // A default argument expression shall be specified only in the
299 // parameter-declaration-clause of a function declaration or in a
300 // template-parameter (14.1). It shall not be specified for a
301 // parameter pack. If it is specified in a
302 // parameter-declaration-clause, it shall not occur within a
303 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000304 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000305 DeclaratorChunk &chunk = D.getTypeObject(i);
306 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000307 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
308 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000309 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000310 if (Param->hasUnparsedDefaultArg()) {
311 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000312 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
313 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
314 delete Toks;
315 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000316 } else if (Param->getDefaultArg()) {
317 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
318 << Param->getDefaultArg()->getSourceRange();
319 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000320 }
321 }
322 }
323 }
324}
325
Chris Lattner3d1cee32008-04-08 05:04:30 +0000326// MergeCXXFunctionDecl - Merge two declarations of the same C++
327// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000328// type. Subroutine of MergeFunctionDecl. Returns true if there was an
329// error, false otherwise.
330bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
331 bool Invalid = false;
332
Chris Lattner3d1cee32008-04-08 05:04:30 +0000333 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000334 // For non-template functions, default arguments can be added in
335 // later declarations of a function in the same
336 // scope. Declarations in different scopes have completely
337 // distinct sets of default arguments. That is, declarations in
338 // inner scopes do not acquire default arguments from
339 // declarations in outer scopes, and vice versa. In a given
340 // function declaration, all parameters subsequent to a
341 // parameter with a default argument shall have default
342 // arguments supplied in this or previous declarations. A
343 // default argument shall not be redefined by a later
344 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000345 //
346 // C++ [dcl.fct.default]p6:
347 // Except for member functions of class templates, the default arguments
348 // in a member function definition that appears outside of the class
349 // definition are added to the set of default arguments provided by the
350 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000351 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
352 ParmVarDecl *OldParam = Old->getParamDecl(p);
353 ParmVarDecl *NewParam = New->getParamDecl(p);
354
Douglas Gregor6cc15182009-09-11 18:44:32 +0000355 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000356
Francois Pichet8d051e02011-04-10 03:03:52 +0000357 unsigned DiagDefaultParamID =
358 diag::err_param_default_argument_redefinition;
359
360 // MSVC accepts that default parameters be redefined for member functions
361 // of template class. The new default parameter's value is ignored.
362 Invalid = true;
363 if (getLangOptions().Microsoft) {
364 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
365 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000366 // Merge the old default argument into the new parameter.
367 NewParam->setHasInheritedDefaultArg();
368 if (OldParam->hasUninstantiatedDefaultArg())
369 NewParam->setUninstantiatedDefaultArg(
370 OldParam->getUninstantiatedDefaultArg());
371 else
372 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000373 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000374 Invalid = false;
375 }
376 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000377
Francois Pichet8cf90492011-04-10 04:58:30 +0000378 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
379 // hint here. Alternatively, we could walk the type-source information
380 // for NewParam to find the last source location in the type... but it
381 // isn't worth the effort right now. This is the kind of test case that
382 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000383 // int f(int);
384 // void g(int (*fp)(int) = f);
385 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000386 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000387 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000388
389 // Look for the function declaration where the default argument was
390 // actually written, which may be a declaration prior to Old.
391 for (FunctionDecl *Older = Old->getPreviousDeclaration();
392 Older; Older = Older->getPreviousDeclaration()) {
393 if (!Older->getParamDecl(p)->hasDefaultArg())
394 break;
395
396 OldParam = Older->getParamDecl(p);
397 }
398
399 Diag(OldParam->getLocation(), diag::note_previous_definition)
400 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000401 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000402 // Merge the old default argument into the new parameter.
403 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000404 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000405 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000406 if (OldParam->hasUninstantiatedDefaultArg())
407 NewParam->setUninstantiatedDefaultArg(
408 OldParam->getUninstantiatedDefaultArg());
409 else
John McCall3d6c1782010-05-04 01:53:42 +0000410 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000411 } else if (NewParam->hasDefaultArg()) {
412 if (New->getDescribedFunctionTemplate()) {
413 // Paragraph 4, quoted above, only applies to non-template functions.
414 Diag(NewParam->getLocation(),
415 diag::err_param_default_argument_template_redecl)
416 << NewParam->getDefaultArgRange();
417 Diag(Old->getLocation(), diag::note_template_prev_declaration)
418 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000419 } else if (New->getTemplateSpecializationKind()
420 != TSK_ImplicitInstantiation &&
421 New->getTemplateSpecializationKind() != TSK_Undeclared) {
422 // C++ [temp.expr.spec]p21:
423 // Default function arguments shall not be specified in a declaration
424 // or a definition for one of the following explicit specializations:
425 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000426 // - the explicit specialization of a member function template;
427 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000428 // template where the class template specialization to which the
429 // member function specialization belongs is implicitly
430 // instantiated.
431 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
432 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
433 << New->getDeclName()
434 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000435 } else if (New->getDeclContext()->isDependentContext()) {
436 // C++ [dcl.fct.default]p6 (DR217):
437 // Default arguments for a member function of a class template shall
438 // be specified on the initial declaration of the member function
439 // within the class template.
440 //
441 // Reading the tea leaves a bit in DR217 and its reference to DR205
442 // leads me to the conclusion that one cannot add default function
443 // arguments for an out-of-line definition of a member function of a
444 // dependent type.
445 int WhichKind = 2;
446 if (CXXRecordDecl *Record
447 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
448 if (Record->getDescribedClassTemplate())
449 WhichKind = 0;
450 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
451 WhichKind = 1;
452 else
453 WhichKind = 2;
454 }
455
456 Diag(NewParam->getLocation(),
457 diag::err_param_default_argument_member_template_redecl)
458 << WhichKind
459 << NewParam->getDefaultArgRange();
460 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000461 }
462 }
463
Douglas Gregore13ad832010-02-12 07:32:17 +0000464 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000465 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000466
Douglas Gregorcda9c672009-02-16 17:45:42 +0000467 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000468}
469
Sebastian Redl60618fa2011-03-12 11:50:43 +0000470/// \brief Merge the exception specifications of two variable declarations.
471///
472/// This is called when there's a redeclaration of a VarDecl. The function
473/// checks if the redeclaration might have an exception specification and
474/// validates compatibility and merges the specs if necessary.
475void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
476 // Shortcut if exceptions are disabled.
477 if (!getLangOptions().CXXExceptions)
478 return;
479
480 assert(Context.hasSameType(New->getType(), Old->getType()) &&
481 "Should only be called if types are otherwise the same.");
482
483 QualType NewType = New->getType();
484 QualType OldType = Old->getType();
485
486 // We're only interested in pointers and references to functions, as well
487 // as pointers to member functions.
488 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
489 NewType = R->getPointeeType();
490 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
491 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
492 NewType = P->getPointeeType();
493 OldType = OldType->getAs<PointerType>()->getPointeeType();
494 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
495 NewType = M->getPointeeType();
496 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
497 }
498
499 if (!NewType->isFunctionProtoType())
500 return;
501
502 // There's lots of special cases for functions. For function pointers, system
503 // libraries are hopefully not as broken so that we don't need these
504 // workarounds.
505 if (CheckEquivalentExceptionSpec(
506 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
507 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
508 New->setInvalidDecl();
509 }
510}
511
Chris Lattner3d1cee32008-04-08 05:04:30 +0000512/// CheckCXXDefaultArguments - Verify that the default arguments for a
513/// function declaration are well-formed according to C++
514/// [dcl.fct.default].
515void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
516 unsigned NumParams = FD->getNumParams();
517 unsigned p;
518
519 // Find first parameter with a default argument
520 for (p = 0; p < NumParams; ++p) {
521 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000522 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000523 break;
524 }
525
526 // C++ [dcl.fct.default]p4:
527 // In a given function declaration, all parameters
528 // subsequent to a parameter with a default argument shall
529 // have default arguments supplied in this or previous
530 // declarations. A default argument shall not be redefined
531 // by a later declaration (not even to the same value).
532 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000533 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000534 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000535 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000536 if (Param->isInvalidDecl())
537 /* We already complained about this parameter. */;
538 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000539 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000540 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000541 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000542 else
Mike Stump1eb44332009-09-09 15:08:12 +0000543 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000544 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner3d1cee32008-04-08 05:04:30 +0000546 LastMissingDefaultArg = p;
547 }
548 }
549
550 if (LastMissingDefaultArg > 0) {
551 // Some default arguments were missing. Clear out all of the
552 // default arguments up to (and including) the last missing
553 // default argument, so that we leave the function parameters
554 // in a semantically valid state.
555 for (p = 0; p <= LastMissingDefaultArg; ++p) {
556 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000557 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000558 Param->setDefaultArg(0);
559 }
560 }
561 }
562}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000563
Douglas Gregorb48fe382008-10-31 09:07:45 +0000564/// isCurrentClassName - Determine whether the identifier II is the
565/// name of the class type currently being defined. In the case of
566/// nested classes, this will only return true if II is the name of
567/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000568bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
569 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000570 assert(getLangOptions().CPlusPlus && "No class names in C!");
571
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000572 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000573 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000574 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000575 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
576 } else
577 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
578
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000579 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000580 return &II == CurDecl->getIdentifier();
581 else
582 return false;
583}
584
Mike Stump1eb44332009-09-09 15:08:12 +0000585/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586///
587/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
588/// and returns NULL otherwise.
589CXXBaseSpecifier *
590Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
591 SourceRange SpecifierRange,
592 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000593 TypeSourceInfo *TInfo,
594 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000595 QualType BaseType = TInfo->getType();
596
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597 // C++ [class.union]p1:
598 // A union shall not have base classes.
599 if (Class->isUnion()) {
600 Diag(Class->getLocation(), diag::err_base_clause_on_union)
601 << SpecifierRange;
602 return 0;
603 }
604
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000605 if (EllipsisLoc.isValid() &&
606 !TInfo->getType()->containsUnexpandedParameterPack()) {
607 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
608 << TInfo->getTypeLoc().getSourceRange();
609 EllipsisLoc = SourceLocation();
610 }
611
Douglas Gregor2943aed2009-03-03 04:44:36 +0000612 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000613 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000614 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000615 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000616
617 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618
619 // Base specifiers must be record types.
620 if (!BaseType->isRecordType()) {
621 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
622 return 0;
623 }
624
625 // C++ [class.union]p1:
626 // A union shall not be used as a base class.
627 if (BaseType->isUnionType()) {
628 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
629 return 0;
630 }
631
632 // C++ [class.derived]p2:
633 // The class-name in a base-specifier shall not be an incompletely
634 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000635 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000636 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000637 << SpecifierRange)) {
638 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 return 0;
John McCall572fc622010-08-17 07:23:57 +0000640 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000641
Eli Friedman1d954f62009-08-15 21:55:26 +0000642 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000643 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000644 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000645 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000646 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000647 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
648 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000649
Anders Carlsson1d209272011-03-25 14:55:14 +0000650 // C++ [class]p3:
651 // If a class is marked final and it appears as a base-type-specifier in
652 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000653 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000654 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
655 << CXXBaseDecl->getDeclName();
656 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
657 << CXXBaseDecl->getDeclName();
658 return 0;
659 }
660
John McCall572fc622010-08-17 07:23:57 +0000661 if (BaseDecl->isInvalidDecl())
662 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000663
664 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000665 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000666 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000667 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000668}
669
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000670/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
671/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000672/// example:
673/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000674/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000675BaseResult
John McCalld226f652010-08-21 09:40:31 +0000676Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000677 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000678 ParsedType basetype, SourceLocation BaseLoc,
679 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000680 if (!classdecl)
681 return true;
682
Douglas Gregor40808ce2009-03-09 23:48:35 +0000683 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000684 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000685 if (!Class)
686 return true;
687
Nick Lewycky56062202010-07-26 16:56:01 +0000688 TypeSourceInfo *TInfo = 0;
689 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000690
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000691 if (EllipsisLoc.isInvalid() &&
692 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000693 UPPC_BaseType))
694 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000695
Douglas Gregor2943aed2009-03-03 04:44:36 +0000696 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000697 Virtual, Access, TInfo,
698 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000699 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Douglas Gregor2943aed2009-03-03 04:44:36 +0000701 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000702}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000703
Douglas Gregor2943aed2009-03-03 04:44:36 +0000704/// \brief Performs the actual work of attaching the given base class
705/// specifiers to a C++ class.
706bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
707 unsigned NumBases) {
708 if (NumBases == 0)
709 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000710
711 // Used to keep track of which base types we have already seen, so
712 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000713 // that the key is always the unqualified canonical type of the base
714 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000715 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
716
717 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000718 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000719 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000720 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000721 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000722 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000723 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000724 if (!Class->hasObjectMember()) {
725 if (const RecordType *FDTTy =
726 NewBaseType.getTypePtr()->getAs<RecordType>())
727 if (FDTTy->getDecl()->hasObjectMember())
728 Class->setHasObjectMember(true);
729 }
730
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000731 if (KnownBaseTypes[NewBaseType]) {
732 // C++ [class.mi]p3:
733 // A class shall not be specified as a direct base class of a
734 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000735 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000736 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000737 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000738 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000739
740 // Delete the duplicate base class specifier; we're going to
741 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000742 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000743
744 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000745 } else {
746 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000747 KnownBaseTypes[NewBaseType] = Bases[idx];
748 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000749 }
750 }
751
752 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000753 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000754
755 // Delete the remaining (good) base class specifiers, since their
756 // data has been copied into the CXXRecordDecl.
757 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000758 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000759
760 return Invalid;
761}
762
763/// ActOnBaseSpecifiers - Attach the given base specifiers to the
764/// class, after checking whether there are any duplicate base
765/// classes.
John McCalld226f652010-08-21 09:40:31 +0000766void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000767 unsigned NumBases) {
768 if (!ClassDecl || !Bases || !NumBases)
769 return;
770
771 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000772 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000773 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000774}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000775
John McCall3cb0ebd2010-03-10 03:28:59 +0000776static CXXRecordDecl *GetClassForType(QualType T) {
777 if (const RecordType *RT = T->getAs<RecordType>())
778 return cast<CXXRecordDecl>(RT->getDecl());
779 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
780 return ICT->getDecl();
781 else
782 return 0;
783}
784
Douglas Gregora8f32e02009-10-06 17:59:45 +0000785/// \brief Determine whether the type \p Derived is a C++ class that is
786/// derived from the type \p Base.
787bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
788 if (!getLangOptions().CPlusPlus)
789 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000790
791 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
792 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000793 return false;
794
John McCall3cb0ebd2010-03-10 03:28:59 +0000795 CXXRecordDecl *BaseRD = GetClassForType(Base);
796 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000797 return false;
798
John McCall86ff3082010-02-04 22:26:26 +0000799 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
800 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000801}
802
803/// \brief Determine whether the type \p Derived is a C++ class that is
804/// derived from the type \p Base.
805bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
806 if (!getLangOptions().CPlusPlus)
807 return false;
808
John McCall3cb0ebd2010-03-10 03:28:59 +0000809 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
810 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000811 return false;
812
John McCall3cb0ebd2010-03-10 03:28:59 +0000813 CXXRecordDecl *BaseRD = GetClassForType(Base);
814 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000815 return false;
816
Douglas Gregora8f32e02009-10-06 17:59:45 +0000817 return DerivedRD->isDerivedFrom(BaseRD, Paths);
818}
819
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000820void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000821 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000822 assert(BasePathArray.empty() && "Base path array must be empty!");
823 assert(Paths.isRecordingPaths() && "Must record paths!");
824
825 const CXXBasePath &Path = Paths.front();
826
827 // We first go backward and check if we have a virtual base.
828 // FIXME: It would be better if CXXBasePath had the base specifier for
829 // the nearest virtual base.
830 unsigned Start = 0;
831 for (unsigned I = Path.size(); I != 0; --I) {
832 if (Path[I - 1].Base->isVirtual()) {
833 Start = I - 1;
834 break;
835 }
836 }
837
838 // Now add all bases.
839 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000840 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000841}
842
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000843/// \brief Determine whether the given base path includes a virtual
844/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000845bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
846 for (CXXCastPath::const_iterator B = BasePath.begin(),
847 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000848 B != BEnd; ++B)
849 if ((*B)->isVirtual())
850 return true;
851
852 return false;
853}
854
Douglas Gregora8f32e02009-10-06 17:59:45 +0000855/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
856/// conversion (where Derived and Base are class types) is
857/// well-formed, meaning that the conversion is unambiguous (and
858/// that all of the base classes are accessible). Returns true
859/// and emits a diagnostic if the code is ill-formed, returns false
860/// otherwise. Loc is the location where this routine should point to
861/// if there is an error, and Range is the source range to highlight
862/// if there is an error.
863bool
864Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000865 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000866 unsigned AmbigiousBaseConvID,
867 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000868 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000869 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000870 // First, determine whether the path from Derived to Base is
871 // ambiguous. This is slightly more expensive than checking whether
872 // the Derived to Base conversion exists, because here we need to
873 // explore multiple paths to determine if there is an ambiguity.
874 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
875 /*DetectVirtual=*/false);
876 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
877 assert(DerivationOkay &&
878 "Can only be used with a derived-to-base conversion");
879 (void)DerivationOkay;
880
881 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000882 if (InaccessibleBaseID) {
883 // Check that the base class can be accessed.
884 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
885 InaccessibleBaseID)) {
886 case AR_inaccessible:
887 return true;
888 case AR_accessible:
889 case AR_dependent:
890 case AR_delayed:
891 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000892 }
John McCall6b2accb2010-02-10 09:31:12 +0000893 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000894
895 // Build a base path if necessary.
896 if (BasePath)
897 BuildBasePathArray(Paths, *BasePath);
898 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000899 }
900
901 // We know that the derived-to-base conversion is ambiguous, and
902 // we're going to produce a diagnostic. Perform the derived-to-base
903 // search just one more time to compute all of the possible paths so
904 // that we can print them out. This is more expensive than any of
905 // the previous derived-to-base checks we've done, but at this point
906 // performance isn't as much of an issue.
907 Paths.clear();
908 Paths.setRecordingPaths(true);
909 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
910 assert(StillOkay && "Can only be used with a derived-to-base conversion");
911 (void)StillOkay;
912
913 // Build up a textual representation of the ambiguous paths, e.g.,
914 // D -> B -> A, that will be used to illustrate the ambiguous
915 // conversions in the diagnostic. We only print one of the paths
916 // to each base class subobject.
917 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
918
919 Diag(Loc, AmbigiousBaseConvID)
920 << Derived << Base << PathDisplayStr << Range << Name;
921 return true;
922}
923
924bool
925Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000926 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000927 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000928 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000929 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000930 IgnoreAccess ? 0
931 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000932 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000933 Loc, Range, DeclarationName(),
934 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000935}
936
937
938/// @brief Builds a string representing ambiguous paths from a
939/// specific derived class to different subobjects of the same base
940/// class.
941///
942/// This function builds a string that can be used in error messages
943/// to show the different paths that one can take through the
944/// inheritance hierarchy to go from the derived class to different
945/// subobjects of a base class. The result looks something like this:
946/// @code
947/// struct D -> struct B -> struct A
948/// struct D -> struct C -> struct A
949/// @endcode
950std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
951 std::string PathDisplayStr;
952 std::set<unsigned> DisplayedPaths;
953 for (CXXBasePaths::paths_iterator Path = Paths.begin();
954 Path != Paths.end(); ++Path) {
955 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
956 // We haven't displayed a path to this particular base
957 // class subobject yet.
958 PathDisplayStr += "\n ";
959 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
960 for (CXXBasePath::const_iterator Element = Path->begin();
961 Element != Path->end(); ++Element)
962 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
963 }
964 }
965
966 return PathDisplayStr;
967}
968
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000969//===----------------------------------------------------------------------===//
970// C++ class member Handling
971//===----------------------------------------------------------------------===//
972
Abramo Bagnara6206d532010-06-05 05:09:32 +0000973/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000974Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
975 SourceLocation ASLoc,
976 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000977 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000978 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000979 ASLoc, ColonLoc);
980 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000981 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000982}
983
Anders Carlsson9e682d92011-01-20 05:57:14 +0000984/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000985void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000986 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
987 if (!MD || !MD->isVirtual())
988 return;
989
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000990 if (MD->isDependentContext())
991 return;
992
Anders Carlsson9e682d92011-01-20 05:57:14 +0000993 // C++0x [class.virtual]p3:
994 // If a virtual function is marked with the virt-specifier override and does
995 // not override a member function of a base class,
996 // the program is ill-formed.
997 bool HasOverriddenMethods =
998 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000999 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001000 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001001 diag::err_function_marked_override_not_overriding)
1002 << MD->getDeclName();
1003 return;
1004 }
1005}
1006
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001007/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1008/// function overrides a virtual member function marked 'final', according to
1009/// C++0x [class.virtual]p3.
1010bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1011 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001012 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001013 return false;
1014
1015 Diag(New->getLocation(), diag::err_final_function_overridden)
1016 << New->getDeclName();
1017 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1018 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001019}
1020
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001021/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1022/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1023/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +00001024/// any.
John McCalld226f652010-08-21 09:40:31 +00001025Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001026Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001027 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +00001028 ExprTy *BW, const VirtSpecifiers &VS,
Sean Hunte4246a62011-05-12 06:15:49 +00001029 ExprTy *InitExpr, bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001030 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001031 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1032 DeclarationName Name = NameInfo.getName();
1033 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001034
1035 // For anonymous bitfields, the location should point to the type.
1036 if (Loc.isInvalid())
1037 Loc = D.getSourceRange().getBegin();
1038
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001039 Expr *BitWidth = static_cast<Expr*>(BW);
1040 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001041
John McCall4bde1e12010-06-04 08:34:12 +00001042 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001043 assert(!DS.isFriendSpecified());
1044
John McCall4bde1e12010-06-04 08:34:12 +00001045 bool isFunc = false;
1046 if (D.isFunctionDeclarator())
1047 isFunc = true;
1048 else if (D.getNumTypeObjects() == 0 &&
1049 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +00001050 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +00001051 isFunc = TDType->isFunctionType();
1052 }
1053
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001054 // C++ 9.2p6: A member shall not be declared to have automatic storage
1055 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001056 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1057 // data members and cannot be applied to names declared const or static,
1058 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001059 switch (DS.getStorageClassSpec()) {
1060 case DeclSpec::SCS_unspecified:
1061 case DeclSpec::SCS_typedef:
1062 case DeclSpec::SCS_static:
1063 // FALL THROUGH.
1064 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001065 case DeclSpec::SCS_mutable:
1066 if (isFunc) {
1067 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001068 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001069 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001070 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Sebastian Redla11f42f2008-11-17 23:24:37 +00001072 // FIXME: It would be nicer if the keyword was ignored only for this
1073 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001074 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001075 }
1076 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001077 default:
1078 if (DS.getStorageClassSpecLoc().isValid())
1079 Diag(DS.getStorageClassSpecLoc(),
1080 diag::err_storageclass_invalid_for_member);
1081 else
1082 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1083 D.getMutableDeclSpec().ClearStorageClassSpecs();
1084 }
1085
Sebastian Redl669d5d72008-11-14 23:42:31 +00001086 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1087 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001088 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001089
1090 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001091 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001092 CXXScopeSpec &SS = D.getCXXScopeSpec();
1093
Douglas Gregor922fff22010-10-13 22:19:53 +00001094 if (SS.isSet() && !SS.isInvalid()) {
1095 // The user provided a superfluous scope specifier inside a class
1096 // definition:
1097 //
1098 // class X {
1099 // int X::member;
1100 // };
1101 DeclContext *DC = 0;
1102 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1103 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1104 << Name << FixItHint::CreateRemoval(SS.getRange());
1105 else
1106 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1107 << Name << SS.getRange();
1108
1109 SS.clear();
1110 }
1111
Douglas Gregor37b372b2009-08-20 22:52:58 +00001112 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001113 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001114 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1115 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001116 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001117 } else {
Sean Hunte4246a62011-05-12 06:15:49 +00001118 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001119 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001120 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001121 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001122
1123 // Non-instance-fields can't have a bitfield.
1124 if (BitWidth) {
1125 if (Member->isInvalidDecl()) {
1126 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001127 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001128 // C++ 9.6p3: A bit-field shall not be a static member.
1129 // "static member 'A' cannot be a bit-field"
1130 Diag(Loc, diag::err_static_not_bitfield)
1131 << Name << BitWidth->getSourceRange();
1132 } else if (isa<TypedefDecl>(Member)) {
1133 // "typedef member 'x' cannot be a bit-field"
1134 Diag(Loc, diag::err_typedef_not_bitfield)
1135 << Name << BitWidth->getSourceRange();
1136 } else {
1137 // A function typedef ("typedef int f(); f a;").
1138 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1139 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001140 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001141 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001142 }
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Chris Lattner8b963ef2009-03-05 23:01:03 +00001144 BitWidth = 0;
1145 Member->setInvalidDecl();
1146 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001147
1148 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Douglas Gregor37b372b2009-08-20 22:52:58 +00001150 // If we have declared a member function template, set the access of the
1151 // templated declaration as well.
1152 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1153 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001154 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001155
Anders Carlssonaae5af22011-01-20 04:34:22 +00001156 if (VS.isOverrideSpecified()) {
1157 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1158 if (!MD || !MD->isVirtual()) {
1159 Diag(Member->getLocStart(),
1160 diag::override_keyword_only_allowed_on_virtual_member_functions)
1161 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001162 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001163 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001164 }
1165 if (VS.isFinalSpecified()) {
1166 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1167 if (!MD || !MD->isVirtual()) {
1168 Diag(Member->getLocStart(),
1169 diag::override_keyword_only_allowed_on_virtual_member_functions)
1170 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001171 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001172 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001173 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001174
Douglas Gregorf5251602011-03-08 17:10:18 +00001175 if (VS.getLastLocation().isValid()) {
1176 // Update the end location of a method that has a virt-specifiers.
1177 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1178 MD->setRangeEnd(VS.getLastLocation());
1179 }
1180
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001181 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001182
Douglas Gregor10bd3682008-11-17 22:58:34 +00001183 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001184
Douglas Gregor021c3b32009-03-11 23:00:04 +00001185 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001186 AddInitializerToDecl(Member, Init, false,
1187 DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001188
Richard Smith483b9f32011-02-21 20:05:19 +00001189 FinalizeDeclaration(Member);
1190
John McCallb25b2952011-02-15 07:12:36 +00001191 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001192 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001193 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001194}
1195
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001196/// \brief Find the direct and/or virtual base specifiers that
1197/// correspond to the given base type, for use in base initialization
1198/// within a constructor.
1199static bool FindBaseInitializer(Sema &SemaRef,
1200 CXXRecordDecl *ClassDecl,
1201 QualType BaseType,
1202 const CXXBaseSpecifier *&DirectBaseSpec,
1203 const CXXBaseSpecifier *&VirtualBaseSpec) {
1204 // First, check for a direct base class.
1205 DirectBaseSpec = 0;
1206 for (CXXRecordDecl::base_class_const_iterator Base
1207 = ClassDecl->bases_begin();
1208 Base != ClassDecl->bases_end(); ++Base) {
1209 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1210 // We found a direct base of this type. That's what we're
1211 // initializing.
1212 DirectBaseSpec = &*Base;
1213 break;
1214 }
1215 }
1216
1217 // Check for a virtual base class.
1218 // FIXME: We might be able to short-circuit this if we know in advance that
1219 // there are no virtual bases.
1220 VirtualBaseSpec = 0;
1221 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1222 // We haven't found a base yet; search the class hierarchy for a
1223 // virtual base class.
1224 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1225 /*DetectVirtual=*/false);
1226 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1227 BaseType, Paths)) {
1228 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1229 Path != Paths.end(); ++Path) {
1230 if (Path->back().Base->isVirtual()) {
1231 VirtualBaseSpec = Path->back().Base;
1232 break;
1233 }
1234 }
1235 }
1236 }
1237
1238 return DirectBaseSpec || VirtualBaseSpec;
1239}
1240
Douglas Gregor7ad83902008-11-05 04:29:56 +00001241/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001242MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001243Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001244 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001245 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001246 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001247 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001248 SourceLocation IdLoc,
1249 SourceLocation LParenLoc,
1250 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001251 SourceLocation RParenLoc,
1252 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001253 if (!ConstructorD)
1254 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001256 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
1258 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001259 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001260 if (!Constructor) {
1261 // The user wrote a constructor initializer on a function that is
1262 // not a C++ constructor. Ignore the error for now, because we may
1263 // have more member initializers coming; we'll diagnose it just
1264 // once in ActOnMemInitializers.
1265 return true;
1266 }
1267
1268 CXXRecordDecl *ClassDecl = Constructor->getParent();
1269
1270 // C++ [class.base.init]p2:
1271 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001272 // constructor's class and, if not found in that scope, are looked
1273 // up in the scope containing the constructor's definition.
1274 // [Note: if the constructor's class contains a member with the
1275 // same name as a direct or virtual base class of the class, a
1276 // mem-initializer-id naming the member or base class and composed
1277 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001278 // mem-initializer-id for the hidden base class may be specified
1279 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001280 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001281 // Look for a member, first.
1282 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001283 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001284 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001285 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001286 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001287
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001288 if (Member) {
1289 if (EllipsisLoc.isValid())
1290 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1291 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1292
Francois Pichet00eb3f92010-12-04 09:14:42 +00001293 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001294 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001295 }
1296
Francois Pichet00eb3f92010-12-04 09:14:42 +00001297 // Handle anonymous union case.
1298 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001299 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1300 if (EllipsisLoc.isValid())
1301 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1302 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1303
Francois Pichet00eb3f92010-12-04 09:14:42 +00001304 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1305 NumArgs, IdLoc,
1306 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001307 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001308 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001309 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001310 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001311 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001312 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001313
1314 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001315 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001316 } else {
1317 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1318 LookupParsedName(R, S, &SS);
1319
1320 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1321 if (!TyD) {
1322 if (R.isAmbiguous()) return true;
1323
John McCallfd225442010-04-09 19:01:14 +00001324 // We don't want access-control diagnostics here.
1325 R.suppressDiagnostics();
1326
Douglas Gregor7a886e12010-01-19 06:46:48 +00001327 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1328 bool NotUnknownSpecialization = false;
1329 DeclContext *DC = computeDeclContext(SS, false);
1330 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1331 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1332
1333 if (!NotUnknownSpecialization) {
1334 // When the scope specifier can refer to a member of an unknown
1335 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001336 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1337 SS.getWithLocInContext(Context),
1338 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001339 if (BaseType.isNull())
1340 return true;
1341
Douglas Gregor7a886e12010-01-19 06:46:48 +00001342 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001343 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001344 }
1345 }
1346
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001347 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001348 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001349 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1350 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001351 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001352 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001353 // We have found a non-static data member with a similar
1354 // name to what was typed; complain and initialize that
1355 // member.
1356 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1357 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001358 << FixItHint::CreateReplacement(R.getNameLoc(),
1359 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001360 Diag(Member->getLocation(), diag::note_previous_decl)
1361 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001362
1363 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1364 LParenLoc, RParenLoc);
1365 }
1366 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1367 const CXXBaseSpecifier *DirectBaseSpec;
1368 const CXXBaseSpecifier *VirtualBaseSpec;
1369 if (FindBaseInitializer(*this, ClassDecl,
1370 Context.getTypeDeclType(Type),
1371 DirectBaseSpec, VirtualBaseSpec)) {
1372 // We have found a direct or virtual base class with a
1373 // similar name to what was typed; complain and initialize
1374 // that base class.
1375 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1376 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001377 << FixItHint::CreateReplacement(R.getNameLoc(),
1378 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001379
1380 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1381 : VirtualBaseSpec;
1382 Diag(BaseSpec->getSourceRange().getBegin(),
1383 diag::note_base_class_specified_here)
1384 << BaseSpec->getType()
1385 << BaseSpec->getSourceRange();
1386
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001387 TyD = Type;
1388 }
1389 }
1390 }
1391
Douglas Gregor7a886e12010-01-19 06:46:48 +00001392 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001393 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1394 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1395 return true;
1396 }
John McCall2b194412009-12-21 10:41:20 +00001397 }
1398
Douglas Gregor7a886e12010-01-19 06:46:48 +00001399 if (BaseType.isNull()) {
1400 BaseType = Context.getTypeDeclType(TyD);
1401 if (SS.isSet()) {
1402 NestedNameSpecifier *Qualifier =
1403 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001404
Douglas Gregor7a886e12010-01-19 06:46:48 +00001405 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001406 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001407 }
John McCall2b194412009-12-21 10:41:20 +00001408 }
1409 }
Mike Stump1eb44332009-09-09 15:08:12 +00001410
John McCalla93c9342009-12-07 02:54:59 +00001411 if (!TInfo)
1412 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001413
John McCalla93c9342009-12-07 02:54:59 +00001414 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001415 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001416}
1417
John McCallb4190042009-11-04 23:02:40 +00001418/// Checks an initializer expression for use of uninitialized fields, such as
1419/// containing the field that is being initialized. Returns true if there is an
1420/// uninitialized field was used an updates the SourceLocation parameter; false
1421/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001422static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001423 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001424 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001425 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1426
Nick Lewycky43ad1822010-06-15 07:32:55 +00001427 if (isa<CallExpr>(S)) {
1428 // Do not descend into function calls or constructors, as the use
1429 // of an uninitialized field may be valid. One would have to inspect
1430 // the contents of the function/ctor to determine if it is safe or not.
1431 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1432 // may be safe, depending on what the function/ctor does.
1433 return false;
1434 }
1435 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1436 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001437
1438 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1439 // The member expression points to a static data member.
1440 assert(VD->isStaticDataMember() &&
1441 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001442 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001443 return false;
1444 }
1445
1446 if (isa<EnumConstantDecl>(RhsField)) {
1447 // The member expression points to an enum.
1448 return false;
1449 }
1450
John McCallb4190042009-11-04 23:02:40 +00001451 if (RhsField == LhsField) {
1452 // Initializing a field with itself. Throw a warning.
1453 // But wait; there are exceptions!
1454 // Exception #1: The field may not belong to this record.
1455 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001456 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001457 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1458 // Even though the field matches, it does not belong to this record.
1459 return false;
1460 }
1461 // None of the exceptions triggered; return true to indicate an
1462 // uninitialized field was used.
1463 *L = ME->getMemberLoc();
1464 return true;
1465 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001466 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001467 // sizeof/alignof doesn't reference contents, do not warn.
1468 return false;
1469 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1470 // address-of doesn't reference contents (the pointer may be dereferenced
1471 // in the same expression but it would be rare; and weird).
1472 if (UOE->getOpcode() == UO_AddrOf)
1473 return false;
John McCallb4190042009-11-04 23:02:40 +00001474 }
John McCall7502c1d2011-02-13 04:07:26 +00001475 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001476 if (!*it) {
1477 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001478 continue;
1479 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001480 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1481 return true;
John McCallb4190042009-11-04 23:02:40 +00001482 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001483 return false;
John McCallb4190042009-11-04 23:02:40 +00001484}
1485
John McCallf312b1e2010-08-26 23:41:50 +00001486MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001487Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001488 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001489 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001490 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001491 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1492 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1493 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001494 "Member must be a FieldDecl or IndirectFieldDecl");
1495
Douglas Gregor464b2f02010-11-05 22:21:31 +00001496 if (Member->isInvalidDecl())
1497 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001498
John McCallb4190042009-11-04 23:02:40 +00001499 // Diagnose value-uses of fields to initialize themselves, e.g.
1500 // foo(foo)
1501 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001502 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001503 for (unsigned i = 0; i < NumArgs; ++i) {
1504 SourceLocation L;
1505 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1506 // FIXME: Return true in the case when other fields are used before being
1507 // uninitialized. For example, let this field be the i'th field. When
1508 // initializing the i'th field, throw a warning if any of the >= i'th
1509 // fields are used, as they are not yet initialized.
1510 // Right now we are only handling the case where the i'th field uses
1511 // itself in its initializer.
1512 Diag(L, diag::warn_field_is_uninit);
1513 }
1514 }
1515
Eli Friedman59c04372009-07-29 19:44:27 +00001516 bool HasDependentArg = false;
1517 for (unsigned i = 0; i < NumArgs; i++)
1518 HasDependentArg |= Args[i]->isTypeDependent();
1519
Chandler Carruth894aed92010-12-06 09:23:57 +00001520 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001521 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001522 // Can't check initialization for a member of dependent type or when
1523 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001524 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1525 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001526
1527 // Erase any temporaries within this evaluation context; we're not
1528 // going to track them in the AST, since we'll be rebuilding the
1529 // ASTs during template instantiation.
1530 ExprTemporaries.erase(
1531 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1532 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001533 } else {
1534 // Initialize the member.
1535 InitializedEntity MemberEntity =
1536 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1537 : InitializedEntity::InitializeMember(IndirectMember, 0);
1538 InitializationKind Kind =
1539 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001540
Chandler Carruth894aed92010-12-06 09:23:57 +00001541 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1542
1543 ExprResult MemberInit =
1544 InitSeq.Perform(*this, MemberEntity, Kind,
1545 MultiExprArg(*this, Args, NumArgs), 0);
1546 if (MemberInit.isInvalid())
1547 return true;
1548
1549 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1550
1551 // C++0x [class.base.init]p7:
1552 // The initialization of each base and member constitutes a
1553 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001554 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001555 if (MemberInit.isInvalid())
1556 return true;
1557
1558 // If we are in a dependent context, template instantiation will
1559 // perform this type-checking again. Just save the arguments that we
1560 // received in a ParenListExpr.
1561 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1562 // of the information that we have about the member
1563 // initializer. However, deconstructing the ASTs is a dicey process,
1564 // and this approach is far more likely to get the corner cases right.
1565 if (CurContext->isDependentContext())
1566 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1567 RParenLoc);
1568 else
1569 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001570 }
1571
Chandler Carruth894aed92010-12-06 09:23:57 +00001572 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001573 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001574 IdLoc, LParenLoc, Init,
1575 RParenLoc);
1576 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001577 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001578 IdLoc, LParenLoc, Init,
1579 RParenLoc);
1580 }
Eli Friedman59c04372009-07-29 19:44:27 +00001581}
1582
John McCallf312b1e2010-08-26 23:41:50 +00001583MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001584Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1585 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001586 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001587 SourceLocation LParenLoc,
1588 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001589 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001590 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1591 if (!LangOpts.CPlusPlus0x)
1592 return Diag(Loc, diag::err_delegation_0x_only)
1593 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001594
Sean Hunt41717662011-02-26 19:13:13 +00001595 // Initialize the object.
1596 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1597 QualType(ClassDecl->getTypeForDecl(), 0));
1598 InitializationKind Kind =
1599 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1600
1601 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1602
1603 ExprResult DelegationInit =
1604 InitSeq.Perform(*this, DelegationEntity, Kind,
1605 MultiExprArg(*this, Args, NumArgs), 0);
1606 if (DelegationInit.isInvalid())
1607 return true;
1608
1609 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001610 CXXConstructorDecl *Constructor
1611 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001612 assert(Constructor && "Delegating constructor with no target?");
1613
1614 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1615
1616 // C++0x [class.base.init]p7:
1617 // The initialization of each base and member constitutes a
1618 // full-expression.
1619 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1620 if (DelegationInit.isInvalid())
1621 return true;
1622
1623 // If we are in a dependent context, template instantiation will
1624 // perform this type-checking again. Just save the arguments that we
1625 // received in a ParenListExpr.
1626 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1627 // of the information that we have about the base
1628 // initializer. However, deconstructing the ASTs is a dicey process,
1629 // and this approach is far more likely to get the corner cases right.
1630 if (CurContext->isDependentContext()) {
1631 ExprResult Init
1632 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1633 NumArgs, RParenLoc));
1634 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1635 Constructor, Init.takeAs<Expr>(),
1636 RParenLoc);
1637 }
1638
1639 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1640 DelegationInit.takeAs<Expr>(),
1641 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001642}
1643
1644MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001645Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001646 Expr **Args, unsigned NumArgs,
1647 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001648 CXXRecordDecl *ClassDecl,
1649 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001650 bool HasDependentArg = false;
1651 for (unsigned i = 0; i < NumArgs; i++)
1652 HasDependentArg |= Args[i]->isTypeDependent();
1653
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001654 SourceLocation BaseLoc
1655 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1656
1657 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1658 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1659 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1660
1661 // C++ [class.base.init]p2:
1662 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001663 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001664 // of that class, the mem-initializer is ill-formed. A
1665 // mem-initializer-list can initialize a base class using any
1666 // name that denotes that base class type.
1667 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1668
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001669 if (EllipsisLoc.isValid()) {
1670 // This is a pack expansion.
1671 if (!BaseType->containsUnexpandedParameterPack()) {
1672 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1673 << SourceRange(BaseLoc, RParenLoc);
1674
1675 EllipsisLoc = SourceLocation();
1676 }
1677 } else {
1678 // Check for any unexpanded parameter packs.
1679 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1680 return true;
1681
1682 for (unsigned I = 0; I != NumArgs; ++I)
1683 if (DiagnoseUnexpandedParameterPack(Args[I]))
1684 return true;
1685 }
1686
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001687 // Check for direct and virtual base classes.
1688 const CXXBaseSpecifier *DirectBaseSpec = 0;
1689 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1690 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001691 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1692 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001693 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1694 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001695
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001696 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1697 VirtualBaseSpec);
1698
1699 // C++ [base.class.init]p2:
1700 // Unless the mem-initializer-id names a nonstatic data member of the
1701 // constructor's class or a direct or virtual base of that class, the
1702 // mem-initializer is ill-formed.
1703 if (!DirectBaseSpec && !VirtualBaseSpec) {
1704 // If the class has any dependent bases, then it's possible that
1705 // one of those types will resolve to the same type as
1706 // BaseType. Therefore, just treat this as a dependent base
1707 // class initialization. FIXME: Should we try to check the
1708 // initialization anyway? It seems odd.
1709 if (ClassDecl->hasAnyDependentBases())
1710 Dependent = true;
1711 else
1712 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1713 << BaseType << Context.getTypeDeclType(ClassDecl)
1714 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1715 }
1716 }
1717
1718 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001719 // Can't check initialization for a base of dependent type or when
1720 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001721 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001722 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1723 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001724
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001725 // Erase any temporaries within this evaluation context; we're not
1726 // going to track them in the AST, since we'll be rebuilding the
1727 // ASTs during template instantiation.
1728 ExprTemporaries.erase(
1729 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1730 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Sean Huntcbb67482011-01-08 20:30:50 +00001732 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001733 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001734 LParenLoc,
1735 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001736 RParenLoc,
1737 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001738 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001739
1740 // C++ [base.class.init]p2:
1741 // If a mem-initializer-id is ambiguous because it designates both
1742 // a direct non-virtual base class and an inherited virtual base
1743 // class, the mem-initializer is ill-formed.
1744 if (DirectBaseSpec && VirtualBaseSpec)
1745 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001746 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001747
1748 CXXBaseSpecifier *BaseSpec
1749 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1750 if (!BaseSpec)
1751 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1752
1753 // Initialize the base.
1754 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001755 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001756 InitializationKind Kind =
1757 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1758
1759 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1760
John McCall60d7b3a2010-08-24 06:29:42 +00001761 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001762 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001763 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001764 if (BaseInit.isInvalid())
1765 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001766
1767 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001768
1769 // C++0x [class.base.init]p7:
1770 // The initialization of each base and member constitutes a
1771 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001772 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001773 if (BaseInit.isInvalid())
1774 return true;
1775
1776 // If we are in a dependent context, template instantiation will
1777 // perform this type-checking again. Just save the arguments that we
1778 // received in a ParenListExpr.
1779 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1780 // of the information that we have about the base
1781 // initializer. However, deconstructing the ASTs is a dicey process,
1782 // and this approach is far more likely to get the corner cases right.
1783 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001784 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001785 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1786 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001787 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001788 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001789 LParenLoc,
1790 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001791 RParenLoc,
1792 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001793 }
1794
Sean Huntcbb67482011-01-08 20:30:50 +00001795 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001796 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001797 LParenLoc,
1798 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001799 RParenLoc,
1800 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001801}
1802
Anders Carlssone5ef7402010-04-23 03:10:23 +00001803/// ImplicitInitializerKind - How an implicit base or member initializer should
1804/// initialize its base or member.
1805enum ImplicitInitializerKind {
1806 IIK_Default,
1807 IIK_Copy,
1808 IIK_Move
1809};
1810
Anders Carlssondefefd22010-04-23 02:00:02 +00001811static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001812BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001813 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001814 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001815 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001816 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001817 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001818 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1819 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001820
John McCall60d7b3a2010-08-24 06:29:42 +00001821 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001822
1823 switch (ImplicitInitKind) {
1824 case IIK_Default: {
1825 InitializationKind InitKind
1826 = InitializationKind::CreateDefault(Constructor->getLocation());
1827 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1828 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001829 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001830 break;
1831 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001832
Anders Carlssone5ef7402010-04-23 03:10:23 +00001833 case IIK_Copy: {
1834 ParmVarDecl *Param = Constructor->getParamDecl(0);
1835 QualType ParamType = Param->getType().getNonReferenceType();
1836
1837 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001838 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001839 Constructor->getLocation(), ParamType,
1840 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001841
Anders Carlssonc7957502010-04-24 22:02:54 +00001842 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001843 QualType ArgTy =
1844 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1845 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001846
1847 CXXCastPath BasePath;
1848 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001849 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1850 CK_UncheckedDerivedToBase,
1851 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001852
Anders Carlssone5ef7402010-04-23 03:10:23 +00001853 InitializationKind InitKind
1854 = InitializationKind::CreateDirect(Constructor->getLocation(),
1855 SourceLocation(), SourceLocation());
1856 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1857 &CopyCtorArg, 1);
1858 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001859 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001860 break;
1861 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001862
Anders Carlssone5ef7402010-04-23 03:10:23 +00001863 case IIK_Move:
1864 assert(false && "Unhandled initializer kind!");
1865 }
John McCall9ae2f072010-08-23 23:25:46 +00001866
Douglas Gregor53c374f2010-12-07 00:41:46 +00001867 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001868 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001869 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001870
Anders Carlssondefefd22010-04-23 02:00:02 +00001871 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001872 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001873 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1874 SourceLocation()),
1875 BaseSpec->isVirtual(),
1876 SourceLocation(),
1877 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001878 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001879 SourceLocation());
1880
Anders Carlssondefefd22010-04-23 02:00:02 +00001881 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001882}
1883
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001884static bool
1885BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001886 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001887 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001888 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001889 if (Field->isInvalidDecl())
1890 return true;
1891
Chandler Carruthf186b542010-06-29 23:50:44 +00001892 SourceLocation Loc = Constructor->getLocation();
1893
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001894 if (ImplicitInitKind == IIK_Copy) {
1895 ParmVarDecl *Param = Constructor->getParamDecl(0);
1896 QualType ParamType = Param->getType().getNonReferenceType();
1897
1898 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001899 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001900 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001901
1902 // Build a reference to this field within the parameter.
1903 CXXScopeSpec SS;
1904 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1905 Sema::LookupMemberName);
1906 MemberLookup.addDecl(Field, AS_public);
1907 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001908 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001909 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001910 ParamType, Loc,
1911 /*IsArrow=*/false,
1912 SS,
1913 /*FirstQualifierInScope=*/0,
1914 MemberLookup,
1915 /*TemplateArgs=*/0);
1916 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001917 return true;
1918
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001919 // When the field we are copying is an array, create index variables for
1920 // each dimension of the array. We use these index variables to subscript
1921 // the source array, and other clients (e.g., CodeGen) will perform the
1922 // necessary iteration with these index variables.
1923 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1924 QualType BaseType = Field->getType();
1925 QualType SizeType = SemaRef.Context.getSizeType();
1926 while (const ConstantArrayType *Array
1927 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1928 // Create the iteration variable for this array index.
1929 IdentifierInfo *IterationVarName = 0;
1930 {
1931 llvm::SmallString<8> Str;
1932 llvm::raw_svector_ostream OS(Str);
1933 OS << "__i" << IndexVariables.size();
1934 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1935 }
1936 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001937 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001938 IterationVarName, SizeType,
1939 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001940 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001941 IndexVariables.push_back(IterationVar);
1942
1943 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001944 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001945 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001946 assert(!IterationVarRef.isInvalid() &&
1947 "Reference to invented variable cannot fail!");
1948
1949 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001950 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001951 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001952 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001953 Loc);
1954 if (CopyCtorArg.isInvalid())
1955 return true;
1956
1957 BaseType = Array->getElementType();
1958 }
1959
1960 // Construct the entity that we will be initializing. For an array, this
1961 // will be first element in the array, which may require several levels
1962 // of array-subscript entities.
1963 llvm::SmallVector<InitializedEntity, 4> Entities;
1964 Entities.reserve(1 + IndexVariables.size());
1965 Entities.push_back(InitializedEntity::InitializeMember(Field));
1966 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1967 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1968 0,
1969 Entities.back()));
1970
1971 // Direct-initialize to use the copy constructor.
1972 InitializationKind InitKind =
1973 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1974
1975 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1976 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1977 &CopyCtorArgE, 1);
1978
John McCall60d7b3a2010-08-24 06:29:42 +00001979 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001980 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001981 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001982 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001983 if (MemberInit.isInvalid())
1984 return true;
1985
1986 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001987 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001988 MemberInit.takeAs<Expr>(), Loc,
1989 IndexVariables.data(),
1990 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001991 return false;
1992 }
1993
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001994 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1995
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001996 QualType FieldBaseElementType =
1997 SemaRef.Context.getBaseElementType(Field->getType());
1998
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001999 if (FieldBaseElementType->isRecordType()) {
2000 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002001 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002002 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002003
2004 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002005 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002006 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002007
Douglas Gregor53c374f2010-12-07 00:41:46 +00002008 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002009 if (MemberInit.isInvalid())
2010 return true;
2011
2012 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002013 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00002014 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002015 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00002016 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002017 return false;
2018 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002019
Sean Hunt1f2f3842011-05-17 00:19:05 +00002020 if (!Field->getParent()->isUnion()) {
2021 if (FieldBaseElementType->isReferenceType()) {
2022 SemaRef.Diag(Constructor->getLocation(),
2023 diag::err_uninitialized_member_in_ctor)
2024 << (int)Constructor->isImplicit()
2025 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2026 << 0 << Field->getDeclName();
2027 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2028 return true;
2029 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002030
Sean Hunt1f2f3842011-05-17 00:19:05 +00002031 if (FieldBaseElementType.isConstQualified()) {
2032 SemaRef.Diag(Constructor->getLocation(),
2033 diag::err_uninitialized_member_in_ctor)
2034 << (int)Constructor->isImplicit()
2035 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2036 << 1 << Field->getDeclName();
2037 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2038 return true;
2039 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002040 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002041
2042 // Nothing to initialize.
2043 CXXMemberInit = 0;
2044 return false;
2045}
John McCallf1860e52010-05-20 23:23:51 +00002046
2047namespace {
2048struct BaseAndFieldInfo {
2049 Sema &S;
2050 CXXConstructorDecl *Ctor;
2051 bool AnyErrorsInInits;
2052 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002053 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2054 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002055
2056 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2057 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2058 // FIXME: Handle implicit move constructors.
2059 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2060 IIK = IIK_Copy;
2061 else
2062 IIK = IIK_Default;
2063 }
2064};
2065}
2066
2067static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2068 FieldDecl *Top, FieldDecl *Field) {
2069
Chandler Carruthe861c602010-06-30 02:59:29 +00002070 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002071 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002072 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002073 return false;
2074 }
2075
2076 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2077 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2078 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002079 CXXRecordDecl *FieldClassDecl
2080 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002081
2082 // Even though union members never have non-trivial default
2083 // constructions in C++03, we still build member initializers for aggregate
2084 // record types which can be union members, and C++0x allows non-trivial
2085 // default constructors for union members, so we ensure that only one
2086 // member is initialized for these.
2087 if (FieldClassDecl->isUnion()) {
2088 // First check for an explicit initializer for one field.
2089 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2090 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002091 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002092 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002093
2094 // Once we've initialized a field of an anonymous union, the union
2095 // field in the class is also initialized, so exit immediately.
2096 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002097 } else if ((*FA)->isAnonymousStructOrUnion()) {
2098 if (CollectFieldInitializer(Info, Top, *FA))
2099 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002100 }
2101 }
2102
2103 // Fallthrough and construct a default initializer for the union as
2104 // a whole, which can call its default constructor if such a thing exists
2105 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2106 // behavior going forward with C++0x, when anonymous unions there are
2107 // finalized, we should revisit this.
2108 } else {
2109 // For structs, we simply descend through to initialize all members where
2110 // necessary.
2111 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2112 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2113 if (CollectFieldInitializer(Info, Top, *FA))
2114 return true;
2115 }
2116 }
John McCallf1860e52010-05-20 23:23:51 +00002117 }
2118
2119 // Don't try to build an implicit initializer if there were semantic
2120 // errors in any of the initializers (and therefore we might be
2121 // missing some that the user actually wrote).
2122 if (Info.AnyErrorsInInits)
2123 return false;
2124
Sean Huntcbb67482011-01-08 20:30:50 +00002125 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002126 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2127 return true;
John McCallf1860e52010-05-20 23:23:51 +00002128
Francois Pichet00eb3f92010-12-04 09:14:42 +00002129 if (Init)
2130 Info.AllToInit.push_back(Init);
2131
John McCallf1860e52010-05-20 23:23:51 +00002132 return false;
2133}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002134
2135bool
2136Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2137 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002138 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002139 Constructor->setNumCtorInitializers(1);
2140 CXXCtorInitializer **initializer =
2141 new (Context) CXXCtorInitializer*[1];
2142 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2143 Constructor->setCtorInitializers(initializer);
2144
Sean Huntb76af9c2011-05-03 23:05:34 +00002145 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2146 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2147 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2148 }
2149
Sean Huntc1598702011-05-05 00:05:47 +00002150 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002151
Sean Hunt059ce0d2011-05-01 07:04:31 +00002152 return false;
2153}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002154
Eli Friedman80c30da2009-11-09 19:20:36 +00002155bool
Sean Huntcbb67482011-01-08 20:30:50 +00002156Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2157 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002158 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002159 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002160 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002161 // Just store the initializers as written, they will be checked during
2162 // instantiation.
2163 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002164 Constructor->setNumCtorInitializers(NumInitializers);
2165 CXXCtorInitializer **baseOrMemberInitializers =
2166 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002167 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002168 NumInitializers * sizeof(CXXCtorInitializer*));
2169 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002170 }
2171
2172 return false;
2173 }
2174
John McCallf1860e52010-05-20 23:23:51 +00002175 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002176
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002177 // We need to build the initializer AST according to order of construction
2178 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002179 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002180 if (!ClassDecl)
2181 return true;
2182
Eli Friedman80c30da2009-11-09 19:20:36 +00002183 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002185 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002186 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002187
2188 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002189 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002190 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002191 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002192 }
2193
Anders Carlsson711f34a2010-04-21 19:52:01 +00002194 // Keep track of the direct virtual bases.
2195 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2196 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2197 E = ClassDecl->bases_end(); I != E; ++I) {
2198 if (I->isVirtual())
2199 DirectVBases.insert(I);
2200 }
2201
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002202 // Push virtual bases before others.
2203 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2204 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2205
Sean Huntcbb67482011-01-08 20:30:50 +00002206 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002207 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2208 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002209 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002210 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002211 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002212 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002213 VBase, IsInheritedVirtualBase,
2214 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002215 HadError = true;
2216 continue;
2217 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002218
John McCallf1860e52010-05-20 23:23:51 +00002219 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002220 }
2221 }
Mike Stump1eb44332009-09-09 15:08:12 +00002222
John McCallf1860e52010-05-20 23:23:51 +00002223 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002224 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2225 E = ClassDecl->bases_end(); Base != E; ++Base) {
2226 // Virtuals are in the virtual base list and already constructed.
2227 if (Base->isVirtual())
2228 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Sean Huntcbb67482011-01-08 20:30:50 +00002230 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002231 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2232 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002233 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002234 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002235 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002236 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002237 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002238 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002239 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002240 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002241
John McCallf1860e52010-05-20 23:23:51 +00002242 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002243 }
2244 }
Mike Stump1eb44332009-09-09 15:08:12 +00002245
John McCallf1860e52010-05-20 23:23:51 +00002246 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002247 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002248 E = ClassDecl->field_end(); Field != E; ++Field) {
2249 if ((*Field)->getType()->isIncompleteArrayType()) {
2250 assert(ClassDecl->hasFlexibleArrayMember() &&
2251 "Incomplete array type is not valid");
2252 continue;
2253 }
John McCallf1860e52010-05-20 23:23:51 +00002254 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002255 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002256 }
Mike Stump1eb44332009-09-09 15:08:12 +00002257
John McCallf1860e52010-05-20 23:23:51 +00002258 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002259 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002260 Constructor->setNumCtorInitializers(NumInitializers);
2261 CXXCtorInitializer **baseOrMemberInitializers =
2262 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002263 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002264 NumInitializers * sizeof(CXXCtorInitializer*));
2265 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002266
John McCallef027fe2010-03-16 21:39:52 +00002267 // Constructors implicitly reference the base and member
2268 // destructors.
2269 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2270 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002271 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002272
2273 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002274}
2275
Eli Friedman6347f422009-07-21 19:28:10 +00002276static void *GetKeyForTopLevelField(FieldDecl *Field) {
2277 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002278 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002279 if (RT->getDecl()->isAnonymousStructOrUnion())
2280 return static_cast<void *>(RT->getDecl());
2281 }
2282 return static_cast<void *>(Field);
2283}
2284
Anders Carlssonea356fb2010-04-02 05:42:15 +00002285static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002286 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002287}
2288
Anders Carlssonea356fb2010-04-02 05:42:15 +00002289static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002290 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002291 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002292 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002293
Eli Friedman6347f422009-07-21 19:28:10 +00002294 // For fields injected into the class via declaration of an anonymous union,
2295 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002296 FieldDecl *Field = Member->getAnyMember();
2297
John McCall3c3ccdb2010-04-10 09:28:51 +00002298 // If the field is a member of an anonymous struct or union, our key
2299 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002300 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002301 if (RD->isAnonymousStructOrUnion()) {
2302 while (true) {
2303 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2304 if (Parent->isAnonymousStructOrUnion())
2305 RD = Parent;
2306 else
2307 break;
2308 }
2309
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002310 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002311 }
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002313 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002314}
2315
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002316static void
2317DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002318 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002319 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002320 unsigned NumInits) {
2321 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002322 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002324 // Don't check initializers order unless the warning is enabled at the
2325 // location of at least one initializer.
2326 bool ShouldCheckOrder = false;
2327 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002328 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002329 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2330 Init->getSourceLocation())
2331 != Diagnostic::Ignored) {
2332 ShouldCheckOrder = true;
2333 break;
2334 }
2335 }
2336 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002337 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002338
John McCalld6ca8da2010-04-10 07:37:23 +00002339 // Build the list of bases and members in the order that they'll
2340 // actually be initialized. The explicit initializers should be in
2341 // this same order but may be missing things.
2342 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Anders Carlsson071d6102010-04-02 03:38:04 +00002344 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2345
John McCalld6ca8da2010-04-10 07:37:23 +00002346 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002347 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002348 ClassDecl->vbases_begin(),
2349 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002350 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002351
John McCalld6ca8da2010-04-10 07:37:23 +00002352 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002353 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002354 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002355 if (Base->isVirtual())
2356 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002357 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002358 }
Mike Stump1eb44332009-09-09 15:08:12 +00002359
John McCalld6ca8da2010-04-10 07:37:23 +00002360 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002361 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2362 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002363 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002364
John McCalld6ca8da2010-04-10 07:37:23 +00002365 unsigned NumIdealInits = IdealInitKeys.size();
2366 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002367
Sean Huntcbb67482011-01-08 20:30:50 +00002368 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002369 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002370 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002371 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002372
2373 // Scan forward to try to find this initializer in the idealized
2374 // initializers list.
2375 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2376 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002377 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002378
2379 // If we didn't find this initializer, it must be because we
2380 // scanned past it on a previous iteration. That can only
2381 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002382 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002383 Sema::SemaDiagnosticBuilder D =
2384 SemaRef.Diag(PrevInit->getSourceLocation(),
2385 diag::warn_initializer_out_of_order);
2386
Francois Pichet00eb3f92010-12-04 09:14:42 +00002387 if (PrevInit->isAnyMemberInitializer())
2388 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002389 else
2390 D << 1 << PrevInit->getBaseClassInfo()->getType();
2391
Francois Pichet00eb3f92010-12-04 09:14:42 +00002392 if (Init->isAnyMemberInitializer())
2393 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002394 else
2395 D << 1 << Init->getBaseClassInfo()->getType();
2396
2397 // Move back to the initializer's location in the ideal list.
2398 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2399 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002400 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002401
2402 assert(IdealIndex != NumIdealInits &&
2403 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002404 }
John McCalld6ca8da2010-04-10 07:37:23 +00002405
2406 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002407 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002408}
2409
John McCall3c3ccdb2010-04-10 09:28:51 +00002410namespace {
2411bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002412 CXXCtorInitializer *Init,
2413 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002414 if (!PrevInit) {
2415 PrevInit = Init;
2416 return false;
2417 }
2418
2419 if (FieldDecl *Field = Init->getMember())
2420 S.Diag(Init->getSourceLocation(),
2421 diag::err_multiple_mem_initialization)
2422 << Field->getDeclName()
2423 << Init->getSourceRange();
2424 else {
John McCallf4c73712011-01-19 06:33:43 +00002425 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002426 assert(BaseClass && "neither field nor base");
2427 S.Diag(Init->getSourceLocation(),
2428 diag::err_multiple_base_initialization)
2429 << QualType(BaseClass, 0)
2430 << Init->getSourceRange();
2431 }
2432 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2433 << 0 << PrevInit->getSourceRange();
2434
2435 return true;
2436}
2437
Sean Huntcbb67482011-01-08 20:30:50 +00002438typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002439typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2440
2441bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002442 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002443 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002444 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002445 RecordDecl *Parent = Field->getParent();
2446 if (!Parent->isAnonymousStructOrUnion())
2447 return false;
2448
2449 NamedDecl *Child = Field;
2450 do {
2451 if (Parent->isUnion()) {
2452 UnionEntry &En = Unions[Parent];
2453 if (En.first && En.first != Child) {
2454 S.Diag(Init->getSourceLocation(),
2455 diag::err_multiple_mem_union_initialization)
2456 << Field->getDeclName()
2457 << Init->getSourceRange();
2458 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2459 << 0 << En.second->getSourceRange();
2460 return true;
2461 } else if (!En.first) {
2462 En.first = Child;
2463 En.second = Init;
2464 }
2465 }
2466
2467 Child = Parent;
2468 Parent = cast<RecordDecl>(Parent->getDeclContext());
2469 } while (Parent->isAnonymousStructOrUnion());
2470
2471 return false;
2472}
2473}
2474
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002475/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002476void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002477 SourceLocation ColonLoc,
2478 MemInitTy **meminits, unsigned NumMemInits,
2479 bool AnyErrors) {
2480 if (!ConstructorDecl)
2481 return;
2482
2483 AdjustDeclIfTemplate(ConstructorDecl);
2484
2485 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002486 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002487
2488 if (!Constructor) {
2489 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2490 return;
2491 }
2492
Sean Huntcbb67482011-01-08 20:30:50 +00002493 CXXCtorInitializer **MemInits =
2494 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002495
2496 // Mapping for the duplicate initializers check.
2497 // For member initializers, this is keyed with a FieldDecl*.
2498 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002499 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002500
2501 // Mapping for the inconsistent anonymous-union initializers check.
2502 RedundantUnionMap MemberUnions;
2503
Anders Carlssonea356fb2010-04-02 05:42:15 +00002504 bool HadError = false;
2505 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002506 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002507
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002508 // Set the source order index.
2509 Init->setSourceOrder(i);
2510
Francois Pichet00eb3f92010-12-04 09:14:42 +00002511 if (Init->isAnyMemberInitializer()) {
2512 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002513 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2514 CheckRedundantUnionInit(*this, Init, MemberUnions))
2515 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002516 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002517 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2518 if (CheckRedundantInit(*this, Init, Members[Key]))
2519 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002520 } else {
2521 assert(Init->isDelegatingInitializer());
2522 // This must be the only initializer
2523 if (i != 0 || NumMemInits > 1) {
2524 Diag(MemInits[0]->getSourceLocation(),
2525 diag::err_delegating_initializer_alone)
2526 << MemInits[0]->getSourceRange();
2527 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002528 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002529 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002530 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002531 // Return immediately as the initializer is set.
2532 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002533 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002534 }
2535
Anders Carlssonea356fb2010-04-02 05:42:15 +00002536 if (HadError)
2537 return;
2538
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002539 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002540
Sean Huntcbb67482011-01-08 20:30:50 +00002541 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002542}
2543
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002544void
John McCallef027fe2010-03-16 21:39:52 +00002545Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2546 CXXRecordDecl *ClassDecl) {
2547 // Ignore dependent contexts.
2548 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002549 return;
John McCall58e6f342010-03-16 05:22:47 +00002550
2551 // FIXME: all the access-control diagnostics are positioned on the
2552 // field/base declaration. That's probably good; that said, the
2553 // user might reasonably want to know why the destructor is being
2554 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002555
Anders Carlsson9f853df2009-11-17 04:44:12 +00002556 // Non-static data members.
2557 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2558 E = ClassDecl->field_end(); I != E; ++I) {
2559 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002560 if (Field->isInvalidDecl())
2561 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002562 QualType FieldType = Context.getBaseElementType(Field->getType());
2563
2564 const RecordType* RT = FieldType->getAs<RecordType>();
2565 if (!RT)
2566 continue;
2567
2568 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002569 if (FieldClassDecl->isInvalidDecl())
2570 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002571 if (FieldClassDecl->hasTrivialDestructor())
2572 continue;
2573
Douglas Gregordb89f282010-07-01 22:47:18 +00002574 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002575 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002576 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002577 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002578 << Field->getDeclName()
2579 << FieldType);
2580
John McCallef027fe2010-03-16 21:39:52 +00002581 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002582 }
2583
John McCall58e6f342010-03-16 05:22:47 +00002584 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2585
Anders Carlsson9f853df2009-11-17 04:44:12 +00002586 // Bases.
2587 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2588 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002589 // Bases are always records in a well-formed non-dependent class.
2590 const RecordType *RT = Base->getType()->getAs<RecordType>();
2591
2592 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002593 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002594 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002595
John McCall58e6f342010-03-16 05:22:47 +00002596 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002597 // If our base class is invalid, we probably can't get its dtor anyway.
2598 if (BaseClassDecl->isInvalidDecl())
2599 continue;
2600 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002601 if (BaseClassDecl->hasTrivialDestructor())
2602 continue;
John McCall58e6f342010-03-16 05:22:47 +00002603
Douglas Gregordb89f282010-07-01 22:47:18 +00002604 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002605 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002606
2607 // FIXME: caret should be on the start of the class name
2608 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002609 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002610 << Base->getType()
2611 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002612
John McCallef027fe2010-03-16 21:39:52 +00002613 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002614 }
2615
2616 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002617 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2618 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002619
2620 // Bases are always records in a well-formed non-dependent class.
2621 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2622
2623 // Ignore direct virtual bases.
2624 if (DirectVirtualBases.count(RT))
2625 continue;
2626
John McCall58e6f342010-03-16 05:22:47 +00002627 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002628 // If our base class is invalid, we probably can't get its dtor anyway.
2629 if (BaseClassDecl->isInvalidDecl())
2630 continue;
2631 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002632 if (BaseClassDecl->hasTrivialDestructor())
2633 continue;
John McCall58e6f342010-03-16 05:22:47 +00002634
Douglas Gregordb89f282010-07-01 22:47:18 +00002635 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002636 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002637 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002638 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002639 << VBase->getType());
2640
John McCallef027fe2010-03-16 21:39:52 +00002641 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002642 }
2643}
2644
John McCalld226f652010-08-21 09:40:31 +00002645void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002646 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002647 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Mike Stump1eb44332009-09-09 15:08:12 +00002649 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002650 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002651 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002652}
2653
Mike Stump1eb44332009-09-09 15:08:12 +00002654bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002655 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002656 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002657 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002658 else
John McCall94c3b562010-08-18 09:41:07 +00002659 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002660}
2661
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002662bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002663 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002664 if (!getLangOptions().CPlusPlus)
2665 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Anders Carlsson11f21a02009-03-23 19:10:31 +00002667 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002668 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Ted Kremenek6217b802009-07-29 21:53:49 +00002670 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002671 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002672 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002673 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002675 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002676 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002677 }
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Ted Kremenek6217b802009-07-29 21:53:49 +00002679 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002680 if (!RT)
2681 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002682
John McCall86ff3082010-02-04 22:26:26 +00002683 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002684
John McCall94c3b562010-08-18 09:41:07 +00002685 // We can't answer whether something is abstract until it has a
2686 // definition. If it's currently being defined, we'll walk back
2687 // over all the declarations when we have a full definition.
2688 const CXXRecordDecl *Def = RD->getDefinition();
2689 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002690 return false;
2691
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002692 if (!RD->isAbstract())
2693 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002694
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002695 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002696 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002697
John McCall94c3b562010-08-18 09:41:07 +00002698 return true;
2699}
2700
2701void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2702 // Check if we've already emitted the list of pure virtual functions
2703 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002704 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002705 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002707 CXXFinalOverriderMap FinalOverriders;
2708 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002710 // Keep a set of seen pure methods so we won't diagnose the same method
2711 // more than once.
2712 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2713
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002714 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2715 MEnd = FinalOverriders.end();
2716 M != MEnd;
2717 ++M) {
2718 for (OverridingMethods::iterator SO = M->second.begin(),
2719 SOEnd = M->second.end();
2720 SO != SOEnd; ++SO) {
2721 // C++ [class.abstract]p4:
2722 // A class is abstract if it contains or inherits at least one
2723 // pure virtual function for which the final overrider is pure
2724 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002726 //
2727 if (SO->second.size() != 1)
2728 continue;
2729
2730 if (!SO->second.front().Method->isPure())
2731 continue;
2732
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002733 if (!SeenPureMethods.insert(SO->second.front().Method))
2734 continue;
2735
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002736 Diag(SO->second.front().Method->getLocation(),
2737 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002738 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002739 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002740 }
2741
2742 if (!PureVirtualClassDiagSet)
2743 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2744 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002745}
2746
Anders Carlsson8211eff2009-03-24 01:19:16 +00002747namespace {
John McCall94c3b562010-08-18 09:41:07 +00002748struct AbstractUsageInfo {
2749 Sema &S;
2750 CXXRecordDecl *Record;
2751 CanQualType AbstractType;
2752 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002753
John McCall94c3b562010-08-18 09:41:07 +00002754 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2755 : S(S), Record(Record),
2756 AbstractType(S.Context.getCanonicalType(
2757 S.Context.getTypeDeclType(Record))),
2758 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002759
John McCall94c3b562010-08-18 09:41:07 +00002760 void DiagnoseAbstractType() {
2761 if (Invalid) return;
2762 S.DiagnoseAbstractType(Record);
2763 Invalid = true;
2764 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002765
John McCall94c3b562010-08-18 09:41:07 +00002766 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2767};
2768
2769struct CheckAbstractUsage {
2770 AbstractUsageInfo &Info;
2771 const NamedDecl *Ctx;
2772
2773 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2774 : Info(Info), Ctx(Ctx) {}
2775
2776 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2777 switch (TL.getTypeLocClass()) {
2778#define ABSTRACT_TYPELOC(CLASS, PARENT)
2779#define TYPELOC(CLASS, PARENT) \
2780 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2781#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002782 }
John McCall94c3b562010-08-18 09:41:07 +00002783 }
Mike Stump1eb44332009-09-09 15:08:12 +00002784
John McCall94c3b562010-08-18 09:41:07 +00002785 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2786 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2787 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002788 if (!TL.getArg(I))
2789 continue;
2790
John McCall94c3b562010-08-18 09:41:07 +00002791 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2792 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002793 }
John McCall94c3b562010-08-18 09:41:07 +00002794 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002795
John McCall94c3b562010-08-18 09:41:07 +00002796 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2797 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2798 }
Mike Stump1eb44332009-09-09 15:08:12 +00002799
John McCall94c3b562010-08-18 09:41:07 +00002800 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2801 // Visit the type parameters from a permissive context.
2802 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2803 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2804 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2805 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2806 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2807 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002808 }
John McCall94c3b562010-08-18 09:41:07 +00002809 }
Mike Stump1eb44332009-09-09 15:08:12 +00002810
John McCall94c3b562010-08-18 09:41:07 +00002811 // Visit pointee types from a permissive context.
2812#define CheckPolymorphic(Type) \
2813 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2814 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2815 }
2816 CheckPolymorphic(PointerTypeLoc)
2817 CheckPolymorphic(ReferenceTypeLoc)
2818 CheckPolymorphic(MemberPointerTypeLoc)
2819 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002820
John McCall94c3b562010-08-18 09:41:07 +00002821 /// Handle all the types we haven't given a more specific
2822 /// implementation for above.
2823 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2824 // Every other kind of type that we haven't called out already
2825 // that has an inner type is either (1) sugar or (2) contains that
2826 // inner type in some way as a subobject.
2827 if (TypeLoc Next = TL.getNextTypeLoc())
2828 return Visit(Next, Sel);
2829
2830 // If there's no inner type and we're in a permissive context,
2831 // don't diagnose.
2832 if (Sel == Sema::AbstractNone) return;
2833
2834 // Check whether the type matches the abstract type.
2835 QualType T = TL.getType();
2836 if (T->isArrayType()) {
2837 Sel = Sema::AbstractArrayType;
2838 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002839 }
John McCall94c3b562010-08-18 09:41:07 +00002840 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2841 if (CT != Info.AbstractType) return;
2842
2843 // It matched; do some magic.
2844 if (Sel == Sema::AbstractArrayType) {
2845 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2846 << T << TL.getSourceRange();
2847 } else {
2848 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2849 << Sel << T << TL.getSourceRange();
2850 }
2851 Info.DiagnoseAbstractType();
2852 }
2853};
2854
2855void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2856 Sema::AbstractDiagSelID Sel) {
2857 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2858}
2859
2860}
2861
2862/// Check for invalid uses of an abstract type in a method declaration.
2863static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2864 CXXMethodDecl *MD) {
2865 // No need to do the check on definitions, which require that
2866 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00002867 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00002868 return;
2869
2870 // For safety's sake, just ignore it if we don't have type source
2871 // information. This should never happen for non-implicit methods,
2872 // but...
2873 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2874 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2875}
2876
2877/// Check for invalid uses of an abstract type within a class definition.
2878static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2879 CXXRecordDecl *RD) {
2880 for (CXXRecordDecl::decl_iterator
2881 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2882 Decl *D = *I;
2883 if (D->isImplicit()) continue;
2884
2885 // Methods and method templates.
2886 if (isa<CXXMethodDecl>(D)) {
2887 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2888 } else if (isa<FunctionTemplateDecl>(D)) {
2889 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2890 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2891
2892 // Fields and static variables.
2893 } else if (isa<FieldDecl>(D)) {
2894 FieldDecl *FD = cast<FieldDecl>(D);
2895 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2896 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2897 } else if (isa<VarDecl>(D)) {
2898 VarDecl *VD = cast<VarDecl>(D);
2899 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2900 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2901
2902 // Nested classes and class templates.
2903 } else if (isa<CXXRecordDecl>(D)) {
2904 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2905 } else if (isa<ClassTemplateDecl>(D)) {
2906 CheckAbstractClassUsage(Info,
2907 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2908 }
2909 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002910}
2911
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002912/// \brief Perform semantic checks on a class definition that has been
2913/// completing, introducing implicitly-declared members, checking for
2914/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002915void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002916 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002917 return;
2918
John McCall94c3b562010-08-18 09:41:07 +00002919 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2920 AbstractUsageInfo Info(*this, Record);
2921 CheckAbstractClassUsage(Info, Record);
2922 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002923
2924 // If this is not an aggregate type and has no user-declared constructor,
2925 // complain about any non-static data members of reference or const scalar
2926 // type, since they will never get initializers.
2927 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2928 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2929 bool Complained = false;
2930 for (RecordDecl::field_iterator F = Record->field_begin(),
2931 FEnd = Record->field_end();
2932 F != FEnd; ++F) {
2933 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002934 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002935 if (!Complained) {
2936 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2937 << Record->getTagKind() << Record;
2938 Complained = true;
2939 }
2940
2941 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2942 << F->getType()->isReferenceType()
2943 << F->getDeclName();
2944 }
2945 }
2946 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002947
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002948 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002949 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002950
2951 if (Record->getIdentifier()) {
2952 // C++ [class.mem]p13:
2953 // If T is the name of a class, then each of the following shall have a
2954 // name different from T:
2955 // - every member of every anonymous union that is a member of class T.
2956 //
2957 // C++ [class.mem]p14:
2958 // In addition, if class T has a user-declared constructor (12.1), every
2959 // non-static data member of class T shall have a name different from T.
2960 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002961 R.first != R.second; ++R.first) {
2962 NamedDecl *D = *R.first;
2963 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2964 isa<IndirectFieldDecl>(D)) {
2965 Diag(D->getLocation(), diag::err_member_name_of_class)
2966 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002967 break;
2968 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002969 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002970 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002971
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002972 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002973 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002974 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002975 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002976 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2977 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2978 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002979
2980 // See if a method overloads virtual methods in a base
2981 /// class without overriding any.
2982 if (!Record->isDependentType()) {
2983 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2984 MEnd = Record->method_end();
2985 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002986 if (!(*M)->isStatic())
2987 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002988 }
2989 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002990
2991 // Declare inherited constructors. We do this eagerly here because:
2992 // - The standard requires an eager diagnostic for conflicting inherited
2993 // constructors from different classes.
2994 // - The lazy declaration of the other implicit constructors is so as to not
2995 // waste space and performance on classes that are not meant to be
2996 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2997 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002998 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00002999
Sean Huntd02fec82011-05-18 01:06:45 +00003000 // Unfortunately, in C++0x mode, we additionally have to declare all
3001 // implicit members in order to ensure we don't get a horrible evil bad
3002 // infinite recursion from ShouldDelete*
3003 if (getLangOptions().CPlusPlus0x)
3004 ForceDeclarationOfImplicitMembers(Record);
3005
Sean Hunt001cad92011-05-10 00:49:42 +00003006 CheckExplicitlyDefaultedMethods(Record);
3007}
3008
3009void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003010 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3011 ME = Record->method_end();
3012 MI != ME; ++MI) {
3013 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3014 switch (getSpecialMember(*MI)) {
3015 case CXXDefaultConstructor:
3016 CheckExplicitlyDefaultedDefaultConstructor(
3017 cast<CXXConstructorDecl>(*MI));
3018 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003019
Sean Huntcb45a0f2011-05-12 22:46:25 +00003020 case CXXDestructor:
3021 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3022 break;
3023
3024 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003025 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3026 break;
3027
Sean Huntcb45a0f2011-05-12 22:46:25 +00003028 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003029 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003030 break;
3031
3032 default:
Sean Hunt2b188082011-05-14 05:23:28 +00003033 // FIXME: Do moves once they exist
Sean Huntcb45a0f2011-05-12 22:46:25 +00003034 llvm_unreachable("non-special member explicitly defaulted!");
3035 }
Sean Hunt001cad92011-05-10 00:49:42 +00003036 }
3037 }
3038
Sean Hunt001cad92011-05-10 00:49:42 +00003039}
3040
3041void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3042 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3043
3044 // Whether this was the first-declared instance of the constructor.
3045 // This affects whether we implicitly add an exception spec (and, eventually,
3046 // constexpr). It is also ill-formed to explicitly default a constructor such
3047 // that it would be deleted. (C++0x [decl.fct.def.default])
3048 bool First = CD == CD->getCanonicalDecl();
3049
Sean Hunt49634cf2011-05-13 06:10:58 +00003050 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003051 if (CD->getNumParams() != 0) {
3052 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3053 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003054 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003055 }
3056
3057 ImplicitExceptionSpecification Spec
3058 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3059 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3060 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3061 *ExceptionType = Context.getFunctionType(
3062 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3063
3064 if (CtorType->hasExceptionSpec()) {
3065 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003066 PDiag(diag::err_incorrect_defaulted_exception_spec)
3067 << 0 /* default constructor */,
Sean Hunt001cad92011-05-10 00:49:42 +00003068 PDiag(),
3069 ExceptionType, SourceLocation(),
3070 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003071 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003072 }
3073 } else if (First) {
3074 // We set the declaration to have the computed exception spec here.
3075 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003076 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003077 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3078 }
Sean Huntca46d132011-05-12 03:51:48 +00003079
Sean Hunt49634cf2011-05-13 06:10:58 +00003080 if (HadError) {
3081 CD->setInvalidDecl();
3082 return;
3083 }
3084
Sean Huntca46d132011-05-12 03:51:48 +00003085 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003086 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003087 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003088 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003089 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Huntcb45a0f2011-05-12 22:46:25 +00003090 << 0 /* default constructor */;
Sean Hunt49634cf2011-05-13 06:10:58 +00003091 CD->setInvalidDecl();
3092 }
3093 }
3094}
3095
3096void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3097 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3098
3099 // Whether this was the first-declared instance of the constructor.
3100 bool First = CD == CD->getCanonicalDecl();
3101
3102 bool HadError = false;
3103 if (CD->getNumParams() != 1) {
3104 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3105 << CD->getSourceRange();
3106 HadError = true;
3107 }
3108
3109 ImplicitExceptionSpecification Spec(Context);
3110 bool Const;
3111 llvm::tie(Spec, Const) =
3112 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3113
3114 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3115 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3116 *ExceptionType = Context.getFunctionType(
3117 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3118
3119 // Check for parameter type matching.
3120 // This is a copy ctor so we know it's a cv-qualified reference to T.
3121 QualType ArgType = CtorType->getArgType(0);
3122 if (ArgType->getPointeeType().isVolatileQualified()) {
3123 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3124 HadError = true;
3125 }
3126 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3127 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3128 HadError = true;
3129 }
3130
3131 if (CtorType->hasExceptionSpec()) {
3132 if (CheckEquivalentExceptionSpec(
3133 PDiag(diag::err_incorrect_defaulted_exception_spec)
3134 << 1 /* copy constructor */,
3135 PDiag(),
3136 ExceptionType, SourceLocation(),
3137 CtorType, CD->getLocation())) {
3138 HadError = true;
3139 }
3140 } else if (First) {
3141 // We set the declaration to have the computed exception spec here.
3142 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003143 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003144 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3145 }
3146
3147 if (HadError) {
3148 CD->setInvalidDecl();
3149 return;
3150 }
3151
3152 if (ShouldDeleteCopyConstructor(CD)) {
3153 if (First) {
3154 CD->setDeletedAsWritten();
3155 } else {
3156 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3157 << 1 /* copy constructor */;
3158 CD->setInvalidDecl();
3159 }
Sean Huntca46d132011-05-12 03:51:48 +00003160 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003161}
Sean Hunt001cad92011-05-10 00:49:42 +00003162
Sean Hunt2b188082011-05-14 05:23:28 +00003163void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3164 assert(MD->isExplicitlyDefaulted());
3165
3166 // Whether this was the first-declared instance of the operator
3167 bool First = MD == MD->getCanonicalDecl();
3168
3169 bool HadError = false;
3170 if (MD->getNumParams() != 1) {
3171 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3172 << MD->getSourceRange();
3173 HadError = true;
3174 }
3175
3176 QualType ReturnType =
3177 MD->getType()->getAs<FunctionType>()->getResultType();
3178 if (!ReturnType->isLValueReferenceType() ||
3179 !Context.hasSameType(
3180 Context.getCanonicalType(ReturnType->getPointeeType()),
3181 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3182 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3183 HadError = true;
3184 }
3185
3186 ImplicitExceptionSpecification Spec(Context);
3187 bool Const;
3188 llvm::tie(Spec, Const) =
3189 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3190
3191 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3192 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3193 *ExceptionType = Context.getFunctionType(
3194 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3195
Sean Hunt2b188082011-05-14 05:23:28 +00003196 QualType ArgType = OperType->getArgType(0);
Sean Huntbe631222011-05-17 20:44:43 +00003197 if (!ArgType->isReferenceType()) {
3198 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003199 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003200 } else {
3201 if (ArgType->getPointeeType().isVolatileQualified()) {
3202 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3203 HadError = true;
3204 }
3205 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3206 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3207 HadError = true;
3208 }
Sean Hunt2b188082011-05-14 05:23:28 +00003209 }
Sean Huntbe631222011-05-17 20:44:43 +00003210
Sean Hunt2b188082011-05-14 05:23:28 +00003211 if (OperType->getTypeQuals()) {
3212 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3213 HadError = true;
3214 }
3215
3216 if (OperType->hasExceptionSpec()) {
3217 if (CheckEquivalentExceptionSpec(
3218 PDiag(diag::err_incorrect_defaulted_exception_spec)
3219 << 2 /* copy assignment operator */,
3220 PDiag(),
3221 ExceptionType, SourceLocation(),
3222 OperType, MD->getLocation())) {
3223 HadError = true;
3224 }
3225 } else if (First) {
3226 // We set the declaration to have the computed exception spec here.
3227 // We duplicate the one parameter type.
3228 EPI.RefQualifier = OperType->getRefQualifier();
3229 EPI.ExtInfo = OperType->getExtInfo();
3230 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3231 }
3232
3233 if (HadError) {
3234 MD->setInvalidDecl();
3235 return;
3236 }
3237
3238 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3239 if (First) {
3240 MD->setDeletedAsWritten();
3241 } else {
3242 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3243 << 2 /* copy assignment operator */;
3244 MD->setInvalidDecl();
3245 }
3246 }
3247}
3248
Sean Huntcb45a0f2011-05-12 22:46:25 +00003249void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3250 assert(DD->isExplicitlyDefaulted());
3251
3252 // Whether this was the first-declared instance of the destructor.
3253 bool First = DD == DD->getCanonicalDecl();
3254
3255 ImplicitExceptionSpecification Spec
3256 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3257 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3258 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3259 *ExceptionType = Context.getFunctionType(
3260 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3261
3262 if (DtorType->hasExceptionSpec()) {
3263 if (CheckEquivalentExceptionSpec(
3264 PDiag(diag::err_incorrect_defaulted_exception_spec)
3265 << 3 /* destructor */,
3266 PDiag(),
3267 ExceptionType, SourceLocation(),
3268 DtorType, DD->getLocation())) {
3269 DD->setInvalidDecl();
3270 return;
3271 }
3272 } else if (First) {
3273 // We set the declaration to have the computed exception spec here.
3274 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003275 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003276 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3277 }
3278
3279 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003280 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003281 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003282 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003283 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3284 << 3 /* destructor */;
Sean Hunt49634cf2011-05-13 06:10:58 +00003285 DD->setInvalidDecl();
3286 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003287 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003288}
3289
Sean Huntcdee3fe2011-05-11 22:34:38 +00003290bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3291 CXXRecordDecl *RD = CD->getParent();
3292 assert(!RD->isDependentType() && "do deletion after instantiation");
3293 if (!LangOpts.CPlusPlus0x)
3294 return false;
3295
Sean Hunt71a682f2011-05-18 03:41:58 +00003296 SourceLocation Loc = CD->getLocation();
3297
Sean Huntcdee3fe2011-05-11 22:34:38 +00003298 // Do access control from the constructor
3299 ContextRAII CtorContext(*this, CD);
3300
3301 bool Union = RD->isUnion();
3302 bool AllConst = true;
3303
Sean Huntcdee3fe2011-05-11 22:34:38 +00003304 // We do this because we should never actually use an anonymous
3305 // union's constructor.
3306 if (Union && RD->isAnonymousStructOrUnion())
3307 return false;
3308
3309 // FIXME: We should put some diagnostic logic right into this function.
3310
3311 // C++0x [class.ctor]/5
3312 // A defaulted default constructor for class X is defined as delete if:
3313
3314 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3315 BE = RD->bases_end();
3316 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003317 // We'll handle this one later
3318 if (BI->isVirtual())
3319 continue;
3320
Sean Huntcdee3fe2011-05-11 22:34:38 +00003321 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3322 assert(BaseDecl && "base isn't a CXXRecordDecl");
3323
3324 // -- any [direct base class] has a type with a destructor that is
3325 // delete or inaccessible from the defaulted default constructor
3326 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3327 if (BaseDtor->isDeleted())
3328 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003329 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003330 AR_accessible)
3331 return true;
3332
Sean Huntcdee3fe2011-05-11 22:34:38 +00003333 // -- any [direct base class either] has no default constructor or
3334 // overload resolution as applied to [its] default constructor
3335 // results in an ambiguity or in a function that is deleted or
3336 // inaccessible from the defaulted default constructor
3337 InitializedEntity BaseEntity =
3338 InitializedEntity::InitializeBase(Context, BI, 0);
3339 InitializationKind Kind =
Sean Hunt71a682f2011-05-18 03:41:58 +00003340 InitializationKind::CreateDirect(Loc, Loc, Loc);
Sean Huntcdee3fe2011-05-11 22:34:38 +00003341
3342 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3343
3344 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3345 return true;
3346 }
3347
3348 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3349 BE = RD->vbases_end();
3350 BI != BE; ++BI) {
3351 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3352 assert(BaseDecl && "base isn't a CXXRecordDecl");
3353
3354 // -- any [virtual base class] has a type with a destructor that is
3355 // delete or inaccessible from the defaulted default constructor
3356 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3357 if (BaseDtor->isDeleted())
3358 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003359 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003360 AR_accessible)
3361 return true;
3362
3363 // -- any [virtual base class either] has no default constructor or
3364 // overload resolution as applied to [its] default constructor
3365 // results in an ambiguity or in a function that is deleted or
3366 // inaccessible from the defaulted default constructor
3367 InitializedEntity BaseEntity =
3368 InitializedEntity::InitializeBase(Context, BI, BI);
3369 InitializationKind Kind =
Sean Hunt71a682f2011-05-18 03:41:58 +00003370 InitializationKind::CreateDirect(Loc, Loc, Loc);
Sean Huntcdee3fe2011-05-11 22:34:38 +00003371
3372 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3373
3374 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3375 return true;
3376 }
3377
3378 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3379 FE = RD->field_end();
3380 FI != FE; ++FI) {
3381 QualType FieldType = Context.getBaseElementType(FI->getType());
3382 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3383
3384 // -- any non-static data member with no brace-or-equal-initializer is of
3385 // reference type
3386 if (FieldType->isReferenceType())
3387 return true;
3388
3389 // -- X is a union and all its variant members are of const-qualified type
3390 // (or array thereof)
3391 if (Union && !FieldType.isConstQualified())
3392 AllConst = false;
3393
3394 if (FieldRecord) {
3395 // -- X is a union-like class that has a variant member with a non-trivial
3396 // default constructor
3397 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3398 return true;
3399
3400 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3401 if (FieldDtor->isDeleted())
3402 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003403 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003404 AR_accessible)
3405 return true;
3406
3407 // -- any non-variant non-static data member of const-qualified type (or
3408 // array thereof) with no brace-or-equal-initializer does not have a
3409 // user-provided default constructor
3410 if (FieldType.isConstQualified() &&
3411 !FieldRecord->hasUserProvidedDefaultConstructor())
3412 return true;
3413
3414 if (!Union && FieldRecord->isUnion() &&
3415 FieldRecord->isAnonymousStructOrUnion()) {
3416 // We're okay to reuse AllConst here since we only care about the
3417 // value otherwise if we're in a union.
3418 AllConst = true;
3419
3420 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3421 UE = FieldRecord->field_end();
3422 UI != UE; ++UI) {
3423 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3424 CXXRecordDecl *UnionFieldRecord =
3425 UnionFieldType->getAsCXXRecordDecl();
3426
3427 if (!UnionFieldType.isConstQualified())
3428 AllConst = false;
3429
3430 if (UnionFieldRecord &&
3431 !UnionFieldRecord->hasTrivialDefaultConstructor())
3432 return true;
3433 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003434
Sean Huntcdee3fe2011-05-11 22:34:38 +00003435 if (AllConst)
3436 return true;
3437
3438 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003439 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003440 continue;
3441 }
3442 }
3443
3444 InitializedEntity MemberEntity =
3445 InitializedEntity::InitializeMember(*FI, 0);
3446 InitializationKind Kind =
Sean Hunt71a682f2011-05-18 03:41:58 +00003447 InitializationKind::CreateDirect(Loc, Loc, Loc);
Sean Huntcdee3fe2011-05-11 22:34:38 +00003448
3449 InitializationSequence InitSeq(*this, MemberEntity, Kind, 0, 0);
3450
3451 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3452 return true;
3453 }
3454
3455 if (Union && AllConst)
3456 return true;
3457
3458 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003459}
3460
Sean Hunt49634cf2011-05-13 06:10:58 +00003461bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Huntd02fec82011-05-18 01:06:45 +00003462 CXXRecordDecl *RD = CD->getParent()->getDefinition();
Sean Hunt49634cf2011-05-13 06:10:58 +00003463 assert(!RD->isDependentType() && "do deletion after instantiation");
Sean Huntd02fec82011-05-18 01:06:45 +00003464 assert(RD);
3465 assert(CD->getParent() == RD);
Sean Hunt49634cf2011-05-13 06:10:58 +00003466 if (!LangOpts.CPlusPlus0x)
3467 return false;
3468
Sean Hunt71a682f2011-05-18 03:41:58 +00003469 SourceLocation Loc = CD->getLocation();
3470
Sean Hunt49634cf2011-05-13 06:10:58 +00003471 // Do access control from the constructor
3472 ContextRAII CtorContext(*this, CD);
3473
Sean Hunt2b188082011-05-14 05:23:28 +00003474 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003475
Sean Hunt2b188082011-05-14 05:23:28 +00003476 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3477 "copy assignment arg has no pointee type");
3478 bool ConstArg =
3479 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Sean Hunt49634cf2011-05-13 06:10:58 +00003480
3481 // We do this because we should never actually use an anonymous
3482 // union's constructor.
3483 if (Union && RD->isAnonymousStructOrUnion())
3484 return false;
3485
3486 // FIXME: We should put some diagnostic logic right into this function.
3487
3488 // C++0x [class.copy]/11
3489 // A defaulted [copy] constructor for class X is defined as delete if X has:
3490
3491 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3492 BE = RD->bases_end();
3493 BI != BE; ++BI) {
3494 // We'll handle this one later
3495 if (BI->isVirtual())
3496 continue;
3497
3498 QualType BaseType = BI->getType();
3499 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3500 assert(BaseDecl && "base isn't a CXXRecordDecl");
3501
3502 // -- any [direct base class] of a type with a destructor that is deleted or
3503 // inaccessible from the defaulted constructor
3504 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3505 if (BaseDtor->isDeleted())
3506 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003507 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003508 AR_accessible)
3509 return true;
3510
3511 // -- a [direct base class] B that cannot be [copied] because overload
3512 // resolution, as applied to B's [copy] constructor, results in an
3513 // ambiguity or a function that is deleted or inaccessible from the
3514 // defaulted constructor
3515 InitializedEntity BaseEntity =
3516 InitializedEntity::InitializeBase(Context, BI, 0);
3517 InitializationKind Kind =
Sean Hunt71a682f2011-05-18 03:41:58 +00003518 InitializationKind::CreateDirect(Loc, Loc, Loc);
Sean Hunt49634cf2011-05-13 06:10:58 +00003519
3520 // Construct a fake expression to perform the copy overloading.
3521 QualType ArgType = BaseType.getUnqualifiedType();
Sean Hunt49634cf2011-05-13 06:10:58 +00003522 if (ConstArg)
3523 ArgType.addConst();
Sean Hunt71a682f2011-05-18 03:41:58 +00003524 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Sean Hunt49634cf2011-05-13 06:10:58 +00003525
3526 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1);
3527
3528 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3529 return true;
3530 }
3531
3532 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3533 BE = RD->vbases_end();
3534 BI != BE; ++BI) {
3535 QualType BaseType = BI->getType();
3536 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3537 assert(BaseDecl && "base isn't a CXXRecordDecl");
3538
3539 // -- any [direct base class] of a type with a destructor that is deleted or
3540 // inaccessible from the defaulted constructor
3541 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3542 if (BaseDtor->isDeleted())
3543 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003544 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003545 AR_accessible)
3546 return true;
3547
3548 // -- a [virtual base class] B that cannot be [copied] because overload
3549 // resolution, as applied to B's [copy] constructor, results in an
3550 // ambiguity or a function that is deleted or inaccessible from the
3551 // defaulted constructor
3552 InitializedEntity BaseEntity =
3553 InitializedEntity::InitializeBase(Context, BI, BI);
3554 InitializationKind Kind =
Sean Hunt71a682f2011-05-18 03:41:58 +00003555 InitializationKind::CreateDirect(Loc, Loc, Loc);
Sean Hunt49634cf2011-05-13 06:10:58 +00003556
3557 // Construct a fake expression to perform the copy overloading.
3558 QualType ArgType = BaseType.getUnqualifiedType();
Sean Hunt49634cf2011-05-13 06:10:58 +00003559 if (ConstArg)
3560 ArgType.addConst();
Sean Hunt71a682f2011-05-18 03:41:58 +00003561 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Sean Hunt49634cf2011-05-13 06:10:58 +00003562
3563 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1);
3564
3565 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3566 return true;
3567 }
3568
3569 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3570 FE = RD->field_end();
3571 FI != FE; ++FI) {
3572 QualType FieldType = Context.getBaseElementType(FI->getType());
3573
3574 // -- for a copy constructor, a non-static data member of rvalue reference
3575 // type
3576 if (FieldType->isRValueReferenceType())
3577 return true;
3578
3579 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3580
3581 if (FieldRecord) {
3582 // This is an anonymous union
3583 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3584 // Anonymous unions inside unions do not variant members create
3585 if (!Union) {
3586 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3587 UE = FieldRecord->field_end();
3588 UI != UE; ++UI) {
3589 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3590 CXXRecordDecl *UnionFieldRecord =
3591 UnionFieldType->getAsCXXRecordDecl();
3592
3593 // -- a variant member with a non-trivial [copy] constructor and X
3594 // is a union-like class
3595 if (UnionFieldRecord &&
3596 !UnionFieldRecord->hasTrivialCopyConstructor())
3597 return true;
3598 }
3599 }
3600
3601 // Don't try to initalize an anonymous union
3602 continue;
3603 } else {
3604 // -- a variant member with a non-trivial [copy] constructor and X is a
3605 // union-like class
3606 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3607 return true;
3608
3609 // -- any [non-static data member] of a type with a destructor that is
3610 // deleted or inaccessible from the defaulted constructor
3611 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3612 if (FieldDtor->isDeleted())
3613 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003614 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003615 AR_accessible)
3616 return true;
3617 }
3618 }
3619
Sean Huntdaebfef2011-05-13 21:10:11 +00003620 llvm::SmallVector<InitializedEntity, 4> Entities;
3621 QualType CurType = FI->getType();
3622 Entities.push_back(InitializedEntity::InitializeMember(*FI, 0));
3623 while (CurType->isArrayType()) {
3624 Entities.push_back(InitializedEntity::InitializeElement(Context, 0,
3625 Entities.back()));
3626 CurType = Context.getAsArrayType(CurType)->getElementType();
3627 }
3628
Sean Hunt49634cf2011-05-13 06:10:58 +00003629 InitializationKind Kind =
Sean Hunt71a682f2011-05-18 03:41:58 +00003630 InitializationKind::CreateDirect(Loc, Loc, Loc);
Sean Hunt49634cf2011-05-13 06:10:58 +00003631
3632 // Construct a fake expression to perform the copy overloading.
3633 QualType ArgType = FieldType;
3634 if (ArgType->isReferenceType())
3635 ArgType = ArgType->getPointeeType();
Sean Hunt2b188082011-05-14 05:23:28 +00003636 else if (ConstArg)
Sean Hunt49634cf2011-05-13 06:10:58 +00003637 ArgType.addConst();
Sean Hunt71a682f2011-05-18 03:41:58 +00003638 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Sean Hunt49634cf2011-05-13 06:10:58 +00003639
Sean Huntdaebfef2011-05-13 21:10:11 +00003640 InitializationSequence InitSeq(*this, Entities.back(), Kind, &Arg, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00003641
3642 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3643 return true;
3644 }
3645
3646 return false;
3647}
3648
Sean Hunt7f410192011-05-14 05:23:24 +00003649bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3650 CXXRecordDecl *RD = MD->getParent();
3651 assert(!RD->isDependentType() && "do deletion after instantiation");
3652 if (!LangOpts.CPlusPlus0x)
3653 return false;
3654
Sean Hunt71a682f2011-05-18 03:41:58 +00003655 SourceLocation Loc = MD->getLocation();
3656
Sean Hunt7f410192011-05-14 05:23:24 +00003657 // Do access control from the constructor
3658 ContextRAII MethodContext(*this, MD);
3659
3660 bool Union = RD->isUnion();
3661
Sean Hunt2b188082011-05-14 05:23:28 +00003662 bool ConstArg =
3663 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Sean Hunt7f410192011-05-14 05:23:24 +00003664
3665 // We do this because we should never actually use an anonymous
3666 // union's constructor.
3667 if (Union && RD->isAnonymousStructOrUnion())
3668 return false;
3669
3670 DeclarationName OperatorName =
3671 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Hunt71a682f2011-05-18 03:41:58 +00003672 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
Sean Hunt7f410192011-05-14 05:23:24 +00003673 R.suppressDiagnostics();
3674
3675 // FIXME: We should put some diagnostic logic right into this function.
3676
3677 // C++0x [class.copy]/11
3678 // A defaulted [copy] assignment operator for class X is defined as deleted
3679 // if X has:
3680
3681 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3682 BE = RD->bases_end();
3683 BI != BE; ++BI) {
3684 // We'll handle this one later
3685 if (BI->isVirtual())
3686 continue;
3687
3688 QualType BaseType = BI->getType();
3689 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3690 assert(BaseDecl && "base isn't a CXXRecordDecl");
3691
3692 // -- a [direct base class] B that cannot be [copied] because overload
3693 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00003694 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00003695 // assignment operator
3696
3697 LookupQualifiedName(R, BaseDecl, false);
3698
3699 // Filter out any result that isn't a copy-assignment operator.
3700 LookupResult::Filter F = R.makeFilter();
3701 while (F.hasNext()) {
3702 NamedDecl *D = F.next();
3703 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3704 if (Method->isCopyAssignmentOperator())
3705 continue;
3706
3707 F.erase();
3708 }
3709 F.done();
3710
3711 // Build a fake argument expression
3712 QualType ArgType = BaseType;
Sean Hunt2b188082011-05-14 05:23:28 +00003713 QualType ThisType = BaseType;
Sean Hunt7f410192011-05-14 05:23:24 +00003714 if (ConstArg)
3715 ArgType.addConst();
Sean Hunt71a682f2011-05-18 03:41:58 +00003716 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3717 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Sean Hunt2b188082011-05-14 05:23:28 +00003718 };
Sean Hunt7f410192011-05-14 05:23:24 +00003719
Sean Hunt71a682f2011-05-18 03:41:58 +00003720 OverloadCandidateSet OCS((Loc));
Sean Hunt7f410192011-05-14 05:23:24 +00003721 OverloadCandidateSet::iterator Best;
3722
Sean Hunt2b188082011-05-14 05:23:28 +00003723 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
Sean Hunt7f410192011-05-14 05:23:24 +00003724
Sean Hunt71a682f2011-05-18 03:41:58 +00003725 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Sean Hunt7f410192011-05-14 05:23:24 +00003726 OR_Success)
3727 return true;
3728 }
3729
3730 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3731 BE = RD->vbases_end();
3732 BI != BE; ++BI) {
3733 QualType BaseType = BI->getType();
3734 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3735 assert(BaseDecl && "base isn't a CXXRecordDecl");
3736
Sean Hunt7f410192011-05-14 05:23:24 +00003737 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00003738 // resolution, as applied to B's [copy] assignment operator, results in
3739 // an ambiguity or a function that is deleted or inaccessible from the
3740 // assignment operator
Sean Hunt7f410192011-05-14 05:23:24 +00003741
Sean Hunt2b188082011-05-14 05:23:28 +00003742 LookupQualifiedName(R, BaseDecl, false);
3743
3744 // Filter out any result that isn't a copy-assignment operator.
3745 LookupResult::Filter F = R.makeFilter();
3746 while (F.hasNext()) {
3747 NamedDecl *D = F.next();
3748 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3749 if (Method->isCopyAssignmentOperator())
3750 continue;
3751
3752 F.erase();
3753 }
3754 F.done();
3755
3756 // Build a fake argument expression
3757 QualType ArgType = BaseType;
3758 QualType ThisType = BaseType;
Sean Hunt7f410192011-05-14 05:23:24 +00003759 if (ConstArg)
3760 ArgType.addConst();
Sean Hunt71a682f2011-05-18 03:41:58 +00003761 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3762 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Sean Hunt2b188082011-05-14 05:23:28 +00003763 };
Sean Hunt7f410192011-05-14 05:23:24 +00003764
Sean Hunt71a682f2011-05-18 03:41:58 +00003765 OverloadCandidateSet OCS((Loc));
Sean Hunt2b188082011-05-14 05:23:28 +00003766 OverloadCandidateSet::iterator Best;
Sean Hunt7f410192011-05-14 05:23:24 +00003767
Sean Hunt2b188082011-05-14 05:23:28 +00003768 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3769
Sean Hunt71a682f2011-05-18 03:41:58 +00003770 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Sean Hunt2b188082011-05-14 05:23:28 +00003771 OR_Success)
Sean Hunt7f410192011-05-14 05:23:24 +00003772 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00003773 }
3774
3775 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3776 FE = RD->field_end();
3777 FI != FE; ++FI) {
3778 QualType FieldType = Context.getBaseElementType(FI->getType());
3779
3780 // -- a non-static data member of reference type
3781 if (FieldType->isReferenceType())
3782 return true;
3783
3784 // -- a non-static data member of const non-class type (or array thereof)
3785 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3786 return true;
3787
3788 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3789
3790 if (FieldRecord) {
3791 // This is an anonymous union
3792 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3793 // Anonymous unions inside unions do not variant members create
3794 if (!Union) {
3795 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3796 UE = FieldRecord->field_end();
3797 UI != UE; ++UI) {
3798 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3799 CXXRecordDecl *UnionFieldRecord =
3800 UnionFieldType->getAsCXXRecordDecl();
3801
3802 // -- a variant member with a non-trivial [copy] assignment operator
3803 // and X is a union-like class
3804 if (UnionFieldRecord &&
3805 !UnionFieldRecord->hasTrivialCopyAssignment())
3806 return true;
3807 }
3808 }
3809
3810 // Don't try to initalize an anonymous union
3811 continue;
3812 // -- a variant member with a non-trivial [copy] assignment operator
3813 // and X is a union-like class
3814 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3815 return true;
3816 }
Sean Hunt7f410192011-05-14 05:23:24 +00003817
Sean Hunt2b188082011-05-14 05:23:28 +00003818 LookupQualifiedName(R, FieldRecord, false);
Sean Hunt7f410192011-05-14 05:23:24 +00003819
Sean Hunt2b188082011-05-14 05:23:28 +00003820 // Filter out any result that isn't a copy-assignment operator.
3821 LookupResult::Filter F = R.makeFilter();
3822 while (F.hasNext()) {
3823 NamedDecl *D = F.next();
3824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3825 if (Method->isCopyAssignmentOperator())
3826 continue;
3827
3828 F.erase();
3829 }
3830 F.done();
Sean Hunt7f410192011-05-14 05:23:24 +00003831
Sean Hunt2b188082011-05-14 05:23:28 +00003832 // Build a fake argument expression
3833 QualType ArgType = FieldType;
3834 QualType ThisType = FieldType;
3835 if (ConstArg)
3836 ArgType.addConst();
Sean Hunt71a682f2011-05-18 03:41:58 +00003837 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3838 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Sean Hunt2b188082011-05-14 05:23:28 +00003839 };
Sean Hunt7f410192011-05-14 05:23:24 +00003840
Sean Hunt71a682f2011-05-18 03:41:58 +00003841 OverloadCandidateSet OCS((Loc));
Sean Hunt2b188082011-05-14 05:23:28 +00003842 OverloadCandidateSet::iterator Best;
3843
3844 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3845
Sean Hunt71a682f2011-05-18 03:41:58 +00003846 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Sean Hunt2b188082011-05-14 05:23:28 +00003847 OR_Success)
3848 return true;
3849 }
Sean Hunt7f410192011-05-14 05:23:24 +00003850 }
3851
3852 return false;
3853}
3854
Sean Huntcb45a0f2011-05-12 22:46:25 +00003855bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3856 CXXRecordDecl *RD = DD->getParent();
3857 assert(!RD->isDependentType() && "do deletion after instantiation");
3858 if (!LangOpts.CPlusPlus0x)
3859 return false;
3860
Sean Hunt71a682f2011-05-18 03:41:58 +00003861 SourceLocation Loc = DD->getLocation();
3862
Sean Huntcb45a0f2011-05-12 22:46:25 +00003863 // Do access control from the destructor
3864 ContextRAII CtorContext(*this, DD);
3865
3866 bool Union = RD->isUnion();
3867
Sean Hunt49634cf2011-05-13 06:10:58 +00003868 // We do this because we should never actually use an anonymous
3869 // union's destructor.
3870 if (Union && RD->isAnonymousStructOrUnion())
3871 return false;
3872
Sean Huntcb45a0f2011-05-12 22:46:25 +00003873 // C++0x [class.dtor]p5
3874 // A defaulted destructor for a class X is defined as deleted if:
3875 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3876 BE = RD->bases_end();
3877 BI != BE; ++BI) {
3878 // We'll handle this one later
3879 if (BI->isVirtual())
3880 continue;
3881
3882 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3883 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3884 assert(BaseDtor && "base has no destructor");
3885
3886 // -- any direct or virtual base class has a deleted destructor or
3887 // a destructor that is inaccessible from the defaulted destructor
3888 if (BaseDtor->isDeleted())
3889 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003890 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003891 AR_accessible)
3892 return true;
3893 }
3894
3895 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3896 BE = RD->vbases_end();
3897 BI != BE; ++BI) {
3898 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3899 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3900 assert(BaseDtor && "base has no destructor");
3901
3902 // -- any direct or virtual base class has a deleted destructor or
3903 // a destructor that is inaccessible from the defaulted destructor
3904 if (BaseDtor->isDeleted())
3905 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003906 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003907 AR_accessible)
3908 return true;
3909 }
3910
3911 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3912 FE = RD->field_end();
3913 FI != FE; ++FI) {
3914 QualType FieldType = Context.getBaseElementType(FI->getType());
3915 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3916 if (FieldRecord) {
3917 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3918 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3919 UE = FieldRecord->field_end();
3920 UI != UE; ++UI) {
3921 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3922 CXXRecordDecl *UnionFieldRecord =
3923 UnionFieldType->getAsCXXRecordDecl();
3924
3925 // -- X is a union-like class that has a variant member with a non-
3926 // trivial destructor.
3927 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3928 return true;
3929 }
3930 // Technically we are supposed to do this next check unconditionally.
3931 // But that makes absolutely no sense.
3932 } else {
3933 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3934
3935 // -- any of the non-static data members has class type M (or array
3936 // thereof) and M has a deleted destructor or a destructor that is
3937 // inaccessible from the defaulted destructor
3938 if (FieldDtor->isDeleted())
3939 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003940 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003941 AR_accessible)
3942 return true;
3943
3944 // -- X is a union-like class that has a variant member with a non-
3945 // trivial destructor.
3946 if (Union && !FieldDtor->isTrivial())
3947 return true;
3948 }
3949 }
3950 }
3951
3952 if (DD->isVirtual()) {
3953 FunctionDecl *OperatorDelete = 0;
3954 DeclarationName Name =
3955 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00003956 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003957 false))
3958 return true;
3959 }
3960
3961
3962 return false;
3963}
3964
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003965/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00003966namespace {
3967 struct FindHiddenVirtualMethodData {
3968 Sema *S;
3969 CXXMethodDecl *Method;
3970 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3971 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3972 };
3973}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003974
3975/// \brief Member lookup function that determines whether a given C++
3976/// method overloads virtual methods in a base class without overriding any,
3977/// to be used with CXXRecordDecl::lookupInBases().
3978static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3979 CXXBasePath &Path,
3980 void *UserData) {
3981 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3982
3983 FindHiddenVirtualMethodData &Data
3984 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3985
3986 DeclarationName Name = Data.Method->getDeclName();
3987 assert(Name.getNameKind() == DeclarationName::Identifier);
3988
3989 bool foundSameNameMethod = false;
3990 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3991 for (Path.Decls = BaseRecord->lookup(Name);
3992 Path.Decls.first != Path.Decls.second;
3993 ++Path.Decls.first) {
3994 NamedDecl *D = *Path.Decls.first;
3995 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003996 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003997 foundSameNameMethod = true;
3998 // Interested only in hidden virtual methods.
3999 if (!MD->isVirtual())
4000 continue;
4001 // If the method we are checking overrides a method from its base
4002 // don't warn about the other overloaded methods.
4003 if (!Data.S->IsOverload(Data.Method, MD, false))
4004 return true;
4005 // Collect the overload only if its hidden.
4006 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4007 overloadedMethods.push_back(MD);
4008 }
4009 }
4010
4011 if (foundSameNameMethod)
4012 Data.OverloadedMethods.append(overloadedMethods.begin(),
4013 overloadedMethods.end());
4014 return foundSameNameMethod;
4015}
4016
4017/// \brief See if a method overloads virtual methods in a base class without
4018/// overriding any.
4019void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4020 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4021 MD->getLocation()) == Diagnostic::Ignored)
4022 return;
4023 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4024 return;
4025
4026 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4027 /*bool RecordPaths=*/false,
4028 /*bool DetectVirtual=*/false);
4029 FindHiddenVirtualMethodData Data;
4030 Data.Method = MD;
4031 Data.S = this;
4032
4033 // Keep the base methods that were overriden or introduced in the subclass
4034 // by 'using' in a set. A base method not in this set is hidden.
4035 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4036 res.first != res.second; ++res.first) {
4037 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4038 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4039 E = MD->end_overridden_methods();
4040 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004041 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004042 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4043 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004044 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004045 }
4046
4047 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4048 !Data.OverloadedMethods.empty()) {
4049 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4050 << MD << (Data.OverloadedMethods.size() > 1);
4051
4052 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4053 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4054 Diag(overloadedMD->getLocation(),
4055 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4056 }
4057 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004058}
4059
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004060void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004061 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004062 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004063 SourceLocation RBrac,
4064 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004065 if (!TagDecl)
4066 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Douglas Gregor42af25f2009-05-11 19:58:34 +00004068 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004069
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004070 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004071 // strict aliasing violation!
4072 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004073 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004074
Douglas Gregor23c94db2010-07-02 17:43:08 +00004075 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004076 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004077}
4078
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004079/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4080/// special functions, such as the default constructor, copy
4081/// constructor, or destructor, to the given C++ class (C++
4082/// [special]p1). This routine can only be executed just before the
4083/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004084void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004085 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004086 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004087
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004088 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004089 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004090
Douglas Gregora376d102010-07-02 21:50:04 +00004091 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4092 ++ASTContext::NumImplicitCopyAssignmentOperators;
4093
4094 // If we have a dynamic class, then the copy assignment operator may be
4095 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4096 // it shows up in the right place in the vtable and that we diagnose
4097 // problems with the implicit exception specification.
4098 if (ClassDecl->isDynamicClass())
4099 DeclareImplicitCopyAssignment(ClassDecl);
4100 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004101
Douglas Gregor4923aa22010-07-02 20:37:36 +00004102 if (!ClassDecl->hasUserDeclaredDestructor()) {
4103 ++ASTContext::NumImplicitDestructors;
4104
4105 // If we have a dynamic class, then the destructor may be virtual, so we
4106 // have to declare the destructor immediately. This ensures that, e.g., it
4107 // shows up in the right place in the vtable and that we diagnose problems
4108 // with the implicit exception specification.
4109 if (ClassDecl->isDynamicClass())
4110 DeclareImplicitDestructor(ClassDecl);
4111 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004112}
4113
Francois Pichet8387e2a2011-04-22 22:18:13 +00004114void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4115 if (!D)
4116 return;
4117
4118 int NumParamList = D->getNumTemplateParameterLists();
4119 for (int i = 0; i < NumParamList; i++) {
4120 TemplateParameterList* Params = D->getTemplateParameterList(i);
4121 for (TemplateParameterList::iterator Param = Params->begin(),
4122 ParamEnd = Params->end();
4123 Param != ParamEnd; ++Param) {
4124 NamedDecl *Named = cast<NamedDecl>(*Param);
4125 if (Named->getDeclName()) {
4126 S->AddDecl(Named);
4127 IdResolver.AddDecl(Named);
4128 }
4129 }
4130 }
4131}
4132
John McCalld226f652010-08-21 09:40:31 +00004133void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004134 if (!D)
4135 return;
4136
4137 TemplateParameterList *Params = 0;
4138 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4139 Params = Template->getTemplateParameters();
4140 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4141 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4142 Params = PartialSpec->getTemplateParameters();
4143 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004144 return;
4145
Douglas Gregor6569d682009-05-27 23:11:45 +00004146 for (TemplateParameterList::iterator Param = Params->begin(),
4147 ParamEnd = Params->end();
4148 Param != ParamEnd; ++Param) {
4149 NamedDecl *Named = cast<NamedDecl>(*Param);
4150 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004151 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004152 IdResolver.AddDecl(Named);
4153 }
4154 }
4155}
4156
John McCalld226f652010-08-21 09:40:31 +00004157void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004158 if (!RecordD) return;
4159 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004160 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004161 PushDeclContext(S, Record);
4162}
4163
John McCalld226f652010-08-21 09:40:31 +00004164void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004165 if (!RecordD) return;
4166 PopDeclContext();
4167}
4168
Douglas Gregor72b505b2008-12-16 21:30:33 +00004169/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4170/// parsing a top-level (non-nested) C++ class, and we are now
4171/// parsing those parts of the given Method declaration that could
4172/// not be parsed earlier (C++ [class.mem]p2), such as default
4173/// arguments. This action should enter the scope of the given
4174/// Method declaration as if we had just parsed the qualified method
4175/// name. However, it should not bring the parameters into scope;
4176/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004177void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004178}
4179
4180/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4181/// C++ method declaration. We're (re-)introducing the given
4182/// function parameter into scope for use in parsing later parts of
4183/// the method declaration. For example, we could see an
4184/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004185void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004186 if (!ParamD)
4187 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004188
John McCalld226f652010-08-21 09:40:31 +00004189 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004190
4191 // If this parameter has an unparsed default argument, clear it out
4192 // to make way for the parsed default argument.
4193 if (Param->hasUnparsedDefaultArg())
4194 Param->setDefaultArg(0);
4195
John McCalld226f652010-08-21 09:40:31 +00004196 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004197 if (Param->getDeclName())
4198 IdResolver.AddDecl(Param);
4199}
4200
4201/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4202/// processing the delayed method declaration for Method. The method
4203/// declaration is now considered finished. There may be a separate
4204/// ActOnStartOfFunctionDef action later (not necessarily
4205/// immediately!) for this method, if it was also defined inside the
4206/// class body.
John McCalld226f652010-08-21 09:40:31 +00004207void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004208 if (!MethodD)
4209 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004210
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004211 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004212
John McCalld226f652010-08-21 09:40:31 +00004213 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004214
4215 // Now that we have our default arguments, check the constructor
4216 // again. It could produce additional diagnostics or affect whether
4217 // the class has implicitly-declared destructors, among other
4218 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004219 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4220 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004221
4222 // Check the default arguments, which we may have added.
4223 if (!Method->isInvalidDecl())
4224 CheckCXXDefaultArguments(Method);
4225}
4226
Douglas Gregor42a552f2008-11-05 20:51:48 +00004227/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004228/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004229/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004230/// emit diagnostics and set the invalid bit to true. In any case, the type
4231/// will be updated to reflect a well-formed type for the constructor and
4232/// returned.
4233QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004234 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004235 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004236
4237 // C++ [class.ctor]p3:
4238 // A constructor shall not be virtual (10.3) or static (9.4). A
4239 // constructor can be invoked for a const, volatile or const
4240 // volatile object. A constructor shall not be declared const,
4241 // volatile, or const volatile (9.3.2).
4242 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004243 if (!D.isInvalidType())
4244 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4245 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4246 << SourceRange(D.getIdentifierLoc());
4247 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004248 }
John McCalld931b082010-08-26 03:08:43 +00004249 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004250 if (!D.isInvalidType())
4251 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4252 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4253 << SourceRange(D.getIdentifierLoc());
4254 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004255 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004256 }
Mike Stump1eb44332009-09-09 15:08:12 +00004257
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004258 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004259 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004260 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004261 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4262 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004263 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004264 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4265 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004266 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004267 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4268 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004269 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004270 }
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Douglas Gregorc938c162011-01-26 05:01:58 +00004272 // C++0x [class.ctor]p4:
4273 // A constructor shall not be declared with a ref-qualifier.
4274 if (FTI.hasRefQualifier()) {
4275 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4276 << FTI.RefQualifierIsLValueRef
4277 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4278 D.setInvalidType();
4279 }
4280
Douglas Gregor42a552f2008-11-05 20:51:48 +00004281 // Rebuild the function type "R" without any type qualifiers (in
4282 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004283 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004284 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004285 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4286 return R;
4287
4288 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4289 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004290 EPI.RefQualifier = RQ_None;
4291
Chris Lattner65401802009-04-25 08:28:21 +00004292 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004293 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004294}
4295
Douglas Gregor72b505b2008-12-16 21:30:33 +00004296/// CheckConstructor - Checks a fully-formed constructor for
4297/// well-formedness, issuing any diagnostics required. Returns true if
4298/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004299void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004300 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004301 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4302 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004303 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004304
4305 // C++ [class.copy]p3:
4306 // A declaration of a constructor for a class X is ill-formed if
4307 // its first parameter is of type (optionally cv-qualified) X and
4308 // either there are no other parameters or else all other
4309 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004310 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004311 ((Constructor->getNumParams() == 1) ||
4312 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004313 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4314 Constructor->getTemplateSpecializationKind()
4315 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004316 QualType ParamType = Constructor->getParamDecl(0)->getType();
4317 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4318 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004319 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004320 const char *ConstRef
4321 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4322 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004323 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004324 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004325
4326 // FIXME: Rather that making the constructor invalid, we should endeavor
4327 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004328 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004329 }
4330 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004331}
4332
John McCall15442822010-08-04 01:04:25 +00004333/// CheckDestructor - Checks a fully-formed destructor definition for
4334/// well-formedness, issuing any diagnostics required. Returns true
4335/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004336bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004337 CXXRecordDecl *RD = Destructor->getParent();
4338
4339 if (Destructor->isVirtual()) {
4340 SourceLocation Loc;
4341
4342 if (!Destructor->isImplicit())
4343 Loc = Destructor->getLocation();
4344 else
4345 Loc = RD->getLocation();
4346
4347 // If we have a virtual destructor, look up the deallocation function
4348 FunctionDecl *OperatorDelete = 0;
4349 DeclarationName Name =
4350 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004351 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004352 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004353
4354 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004355
4356 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004357 }
Anders Carlsson37909802009-11-30 21:24:50 +00004358
4359 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004360}
4361
Mike Stump1eb44332009-09-09 15:08:12 +00004362static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004363FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4364 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4365 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004366 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004367}
4368
Douglas Gregor42a552f2008-11-05 20:51:48 +00004369/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4370/// the well-formednes of the destructor declarator @p D with type @p
4371/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004372/// emit diagnostics and set the declarator to invalid. Even if this happens,
4373/// will be updated to reflect a well-formed type for the destructor and
4374/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004375QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004376 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004377 // C++ [class.dtor]p1:
4378 // [...] A typedef-name that names a class is a class-name
4379 // (7.1.3); however, a typedef-name that names a class shall not
4380 // be used as the identifier in the declarator for a destructor
4381 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004382 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004383 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004384 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004385 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004386 else if (const TemplateSpecializationType *TST =
4387 DeclaratorType->getAs<TemplateSpecializationType>())
4388 if (TST->isTypeAlias())
4389 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4390 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004391
4392 // C++ [class.dtor]p2:
4393 // A destructor is used to destroy objects of its class type. A
4394 // destructor takes no parameters, and no return type can be
4395 // specified for it (not even void). The address of a destructor
4396 // shall not be taken. A destructor shall not be static. A
4397 // destructor can be invoked for a const, volatile or const
4398 // volatile object. A destructor shall not be declared const,
4399 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004400 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004401 if (!D.isInvalidType())
4402 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4403 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004404 << SourceRange(D.getIdentifierLoc())
4405 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4406
John McCalld931b082010-08-26 03:08:43 +00004407 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004408 }
Chris Lattner65401802009-04-25 08:28:21 +00004409 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004410 // Destructors don't have return types, but the parser will
4411 // happily parse something like:
4412 //
4413 // class X {
4414 // float ~X();
4415 // };
4416 //
4417 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004418 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4419 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4420 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004421 }
Mike Stump1eb44332009-09-09 15:08:12 +00004422
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004423 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004424 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004425 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004426 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4427 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004428 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004429 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4430 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004431 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004432 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4433 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004434 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004435 }
4436
Douglas Gregorc938c162011-01-26 05:01:58 +00004437 // C++0x [class.dtor]p2:
4438 // A destructor shall not be declared with a ref-qualifier.
4439 if (FTI.hasRefQualifier()) {
4440 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4441 << FTI.RefQualifierIsLValueRef
4442 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4443 D.setInvalidType();
4444 }
4445
Douglas Gregor42a552f2008-11-05 20:51:48 +00004446 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004447 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004448 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4449
4450 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004451 FTI.freeArgs();
4452 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004453 }
4454
Mike Stump1eb44332009-09-09 15:08:12 +00004455 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004456 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004457 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004458 D.setInvalidType();
4459 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004460
4461 // Rebuild the function type "R" without any type qualifiers or
4462 // parameters (in case any of the errors above fired) and with
4463 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004464 // types.
John McCalle23cf432010-12-14 08:05:40 +00004465 if (!D.isInvalidType())
4466 return R;
4467
Douglas Gregord92ec472010-07-01 05:10:53 +00004468 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004469 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4470 EPI.Variadic = false;
4471 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004472 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004473 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004474}
4475
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004476/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4477/// well-formednes of the conversion function declarator @p D with
4478/// type @p R. If there are any errors in the declarator, this routine
4479/// will emit diagnostics and return true. Otherwise, it will return
4480/// false. Either way, the type @p R will be updated to reflect a
4481/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00004482void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00004483 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004484 // C++ [class.conv.fct]p1:
4485 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00004486 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00004487 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00004488 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00004489 if (!D.isInvalidType())
4490 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4491 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4492 << SourceRange(D.getIdentifierLoc());
4493 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004494 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004495 }
John McCalla3f81372010-04-13 00:04:31 +00004496
4497 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4498
Chris Lattner6e475012009-04-25 08:35:12 +00004499 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004500 // Conversion functions don't have return types, but the parser will
4501 // happily parse something like:
4502 //
4503 // class X {
4504 // float operator bool();
4505 // };
4506 //
4507 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004508 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4509 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4510 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00004511 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004512 }
4513
John McCalla3f81372010-04-13 00:04:31 +00004514 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4515
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004516 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00004517 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004518 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4519
4520 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004521 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00004522 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00004523 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004524 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00004525 D.setInvalidType();
4526 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004527
John McCalla3f81372010-04-13 00:04:31 +00004528 // Diagnose "&operator bool()" and other such nonsense. This
4529 // is actually a gcc extension which we don't support.
4530 if (Proto->getResultType() != ConvType) {
4531 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4532 << Proto->getResultType();
4533 D.setInvalidType();
4534 ConvType = Proto->getResultType();
4535 }
4536
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004537 // C++ [class.conv.fct]p4:
4538 // The conversion-type-id shall not represent a function type nor
4539 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004540 if (ConvType->isArrayType()) {
4541 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4542 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004543 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004544 } else if (ConvType->isFunctionType()) {
4545 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4546 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004547 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004548 }
4549
4550 // Rebuild the function type "R" without any parameters (in case any
4551 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00004552 // return type.
John McCalle23cf432010-12-14 08:05:40 +00004553 if (D.isInvalidType())
4554 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004555
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004556 // C++0x explicit conversion operators.
4557 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00004558 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004559 diag::warn_explicit_conversion_functions)
4560 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004561}
4562
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004563/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4564/// the declaration of the given C++ conversion function. This routine
4565/// is responsible for recording the conversion function in the C++
4566/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00004567Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004568 assert(Conversion && "Expected to receive a conversion function declaration");
4569
Douglas Gregor9d350972008-12-12 08:25:50 +00004570 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004571
4572 // Make sure we aren't redeclaring the conversion function.
4573 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004574
4575 // C++ [class.conv.fct]p1:
4576 // [...] A conversion function is never used to convert a
4577 // (possibly cv-qualified) object to the (possibly cv-qualified)
4578 // same object type (or a reference to it), to a (possibly
4579 // cv-qualified) base class of that type (or a reference to it),
4580 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00004581 // FIXME: Suppress this warning if the conversion function ends up being a
4582 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00004583 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004584 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00004585 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004586 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004587 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4588 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00004589 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004590 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004591 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4592 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00004593 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004594 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004595 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00004596 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004597 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004598 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00004599 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004600 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004601 }
4602
Douglas Gregore80622f2010-09-29 04:25:11 +00004603 if (FunctionTemplateDecl *ConversionTemplate
4604 = Conversion->getDescribedFunctionTemplate())
4605 return ConversionTemplate;
4606
John McCalld226f652010-08-21 09:40:31 +00004607 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004608}
4609
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004610//===----------------------------------------------------------------------===//
4611// Namespace Handling
4612//===----------------------------------------------------------------------===//
4613
John McCallea318642010-08-26 09:15:37 +00004614
4615
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004616/// ActOnStartNamespaceDef - This is called at the start of a namespace
4617/// definition.
John McCalld226f652010-08-21 09:40:31 +00004618Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00004619 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004620 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00004621 SourceLocation IdentLoc,
4622 IdentifierInfo *II,
4623 SourceLocation LBrace,
4624 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004625 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4626 // For anonymous namespace, take the location of the left brace.
4627 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00004628 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004629 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004630 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004631
4632 Scope *DeclRegionScope = NamespcScope->getParent();
4633
Anders Carlsson2a3503d2010-02-07 01:09:23 +00004634 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4635
John McCall90f14502010-12-10 02:59:44 +00004636 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4637 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004638
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004639 if (II) {
4640 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00004641 // The identifier in an original-namespace-definition shall not
4642 // have been previously defined in the declarative region in
4643 // which the original-namespace-definition appears. The
4644 // identifier in an original-namespace-definition is the name of
4645 // the namespace. Subsequently in that declarative region, it is
4646 // treated as an original-namespace-name.
4647 //
4648 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00004649 // look through using directives, just look for any ordinary names.
4650
4651 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4652 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4653 Decl::IDNS_Namespace;
4654 NamedDecl *PrevDecl = 0;
4655 for (DeclContext::lookup_result R
4656 = CurContext->getRedeclContext()->lookup(II);
4657 R.first != R.second; ++R.first) {
4658 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4659 PrevDecl = *R.first;
4660 break;
4661 }
4662 }
4663
Douglas Gregor44b43212008-12-11 16:49:14 +00004664 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4665 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004666 if (Namespc->isInline() != OrigNS->isInline()) {
4667 // inline-ness must match
4668 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4669 << Namespc->isInline();
4670 Diag(OrigNS->getLocation(), diag::note_previous_definition);
4671 Namespc->setInvalidDecl();
4672 // Recover by ignoring the new namespace's inline status.
4673 Namespc->setInline(OrigNS->isInline());
4674 }
4675
Douglas Gregor44b43212008-12-11 16:49:14 +00004676 // Attach this namespace decl to the chain of extended namespace
4677 // definitions.
4678 OrigNS->setNextNamespace(Namespc);
4679 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004680
Mike Stump1eb44332009-09-09 15:08:12 +00004681 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00004682 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00004683 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00004684 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004685 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004686 } else if (PrevDecl) {
4687 // This is an invalid name redefinition.
4688 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4689 << Namespc->getDeclName();
4690 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4691 Namespc->setInvalidDecl();
4692 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004693 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004694 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004695 // This is the first "real" definition of the namespace "std", so update
4696 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004697 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004698 // We had already defined a dummy namespace "std". Link this new
4699 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004700 StdNS->setNextNamespace(Namespc);
4701 StdNS->setLocation(IdentLoc);
4702 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004703 }
4704
4705 // Make our StdNamespace cache point at the first real definition of the
4706 // "std" namespace.
4707 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00004708 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004709
4710 PushOnScopeChains(Namespc, DeclRegionScope);
4711 } else {
John McCall9aeed322009-10-01 00:25:31 +00004712 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00004713 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00004714
4715 // Link the anonymous namespace into its parent.
4716 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004717 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00004718 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4719 PrevDecl = TU->getAnonymousNamespace();
4720 TU->setAnonymousNamespace(Namespc);
4721 } else {
4722 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4723 PrevDecl = ND->getAnonymousNamespace();
4724 ND->setAnonymousNamespace(Namespc);
4725 }
4726
4727 // Link the anonymous namespace with its previous declaration.
4728 if (PrevDecl) {
4729 assert(PrevDecl->isAnonymousNamespace());
4730 assert(!PrevDecl->getNextNamespace());
4731 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4732 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004733
4734 if (Namespc->isInline() != PrevDecl->isInline()) {
4735 // inline-ness must match
4736 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4737 << Namespc->isInline();
4738 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4739 Namespc->setInvalidDecl();
4740 // Recover by ignoring the new namespace's inline status.
4741 Namespc->setInline(PrevDecl->isInline());
4742 }
John McCall5fdd7642009-12-16 02:06:49 +00004743 }
John McCall9aeed322009-10-01 00:25:31 +00004744
Douglas Gregora4181472010-03-24 00:46:35 +00004745 CurContext->addDecl(Namespc);
4746
John McCall9aeed322009-10-01 00:25:31 +00004747 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4748 // behaves as if it were replaced by
4749 // namespace unique { /* empty body */ }
4750 // using namespace unique;
4751 // namespace unique { namespace-body }
4752 // where all occurrences of 'unique' in a translation unit are
4753 // replaced by the same identifier and this identifier differs
4754 // from all other identifiers in the entire program.
4755
4756 // We just create the namespace with an empty name and then add an
4757 // implicit using declaration, just like the standard suggests.
4758 //
4759 // CodeGen enforces the "universally unique" aspect by giving all
4760 // declarations semantically contained within an anonymous
4761 // namespace internal linkage.
4762
John McCall5fdd7642009-12-16 02:06:49 +00004763 if (!PrevDecl) {
4764 UsingDirectiveDecl* UD
4765 = UsingDirectiveDecl::Create(Context, CurContext,
4766 /* 'using' */ LBrace,
4767 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00004768 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00004769 /* identifier */ SourceLocation(),
4770 Namespc,
4771 /* Ancestor */ CurContext);
4772 UD->setImplicit();
4773 CurContext->addDecl(UD);
4774 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004775 }
4776
4777 // Although we could have an invalid decl (i.e. the namespace name is a
4778 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00004779 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4780 // for the namespace has the declarations that showed up in that particular
4781 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00004782 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00004783 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004784}
4785
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004786/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4787/// is a namespace alias, returns the namespace it points to.
4788static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4789 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4790 return AD->getNamespace();
4791 return dyn_cast_or_null<NamespaceDecl>(D);
4792}
4793
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004794/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4795/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00004796void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004797 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4798 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004799 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004800 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004801 if (Namespc->hasAttr<VisibilityAttr>())
4802 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004803}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004804
John McCall384aff82010-08-25 07:42:41 +00004805CXXRecordDecl *Sema::getStdBadAlloc() const {
4806 return cast_or_null<CXXRecordDecl>(
4807 StdBadAlloc.get(Context.getExternalSource()));
4808}
4809
4810NamespaceDecl *Sema::getStdNamespace() const {
4811 return cast_or_null<NamespaceDecl>(
4812 StdNamespace.get(Context.getExternalSource()));
4813}
4814
Douglas Gregor66992202010-06-29 17:53:46 +00004815/// \brief Retrieve the special "std" namespace, which may require us to
4816/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004817NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00004818 if (!StdNamespace) {
4819 // The "std" namespace has not yet been defined, so build one implicitly.
4820 StdNamespace = NamespaceDecl::Create(Context,
4821 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004822 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00004823 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004824 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00004825 }
4826
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004827 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00004828}
4829
Douglas Gregor9172aa62011-03-26 22:25:30 +00004830/// \brief Determine whether a using statement is in a context where it will be
4831/// apply in all contexts.
4832static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4833 switch (CurContext->getDeclKind()) {
4834 case Decl::TranslationUnit:
4835 return true;
4836 case Decl::LinkageSpec:
4837 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4838 default:
4839 return false;
4840 }
4841}
4842
John McCalld226f652010-08-21 09:40:31 +00004843Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004844 SourceLocation UsingLoc,
4845 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004846 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004847 SourceLocation IdentLoc,
4848 IdentifierInfo *NamespcName,
4849 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00004850 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4851 assert(NamespcName && "Invalid NamespcName.");
4852 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00004853
4854 // This can only happen along a recovery path.
4855 while (S->getFlags() & Scope::TemplateParamScope)
4856 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004857 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00004858
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004859 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00004860 NestedNameSpecifier *Qualifier = 0;
4861 if (SS.isSet())
4862 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4863
Douglas Gregoreb11cd02009-01-14 22:20:51 +00004864 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004865 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4866 LookupParsedName(R, S, &SS);
4867 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004868 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004869
Douglas Gregor66992202010-06-29 17:53:46 +00004870 if (R.empty()) {
4871 // Allow "using namespace std;" or "using namespace ::std;" even if
4872 // "std" hasn't been defined yet, for GCC compatibility.
4873 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4874 NamespcName->isStr("std")) {
4875 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004876 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00004877 R.resolveKind();
4878 }
4879 // Otherwise, attempt typo correction.
4880 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4881 CTC_NoKeywords, 0)) {
4882 if (R.getAsSingle<NamespaceDecl>() ||
4883 R.getAsSingle<NamespaceAliasDecl>()) {
4884 if (DeclContext *DC = computeDeclContext(SS, false))
4885 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4886 << NamespcName << DC << Corrected << SS.getRange()
4887 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4888 else
4889 Diag(IdentLoc, diag::err_using_directive_suggest)
4890 << NamespcName << Corrected
4891 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4892 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4893 << Corrected;
4894
4895 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004896 } else {
4897 R.clear();
4898 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00004899 }
4900 }
4901 }
4902
John McCallf36e02d2009-10-09 21:13:30 +00004903 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004904 NamedDecl *Named = R.getFoundDecl();
4905 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4906 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004907 // C++ [namespace.udir]p1:
4908 // A using-directive specifies that the names in the nominated
4909 // namespace can be used in the scope in which the
4910 // using-directive appears after the using-directive. During
4911 // unqualified name lookup (3.4.1), the names appear as if they
4912 // were declared in the nearest enclosing namespace which
4913 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00004914 // namespace. [Note: in this context, "contains" means "contains
4915 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004916
4917 // Find enclosing context containing both using-directive and
4918 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004919 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004920 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4921 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4922 CommonAncestor = CommonAncestor->getParent();
4923
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004924 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00004925 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004926 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004927
Douglas Gregor9172aa62011-03-26 22:25:30 +00004928 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00004929 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004930 Diag(IdentLoc, diag::warn_using_directive_in_header);
4931 }
4932
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004933 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004934 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00004935 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00004936 }
4937
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004938 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00004939 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004940}
4941
4942void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4943 // If scope has associated entity, then using directive is at namespace
4944 // or translation unit scope. We add UsingDirectiveDecls, into
4945 // it's lookup structure.
4946 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004947 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004948 else
4949 // Otherwise it is block-sope. using-directives will affect lookup
4950 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00004951 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004952}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004953
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004954
John McCalld226f652010-08-21 09:40:31 +00004955Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00004956 AccessSpecifier AS,
4957 bool HasUsingKeyword,
4958 SourceLocation UsingLoc,
4959 CXXScopeSpec &SS,
4960 UnqualifiedId &Name,
4961 AttributeList *AttrList,
4962 bool IsTypeName,
4963 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004964 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00004965
Douglas Gregor12c118a2009-11-04 16:30:06 +00004966 switch (Name.getKind()) {
4967 case UnqualifiedId::IK_Identifier:
4968 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00004969 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004970 case UnqualifiedId::IK_ConversionFunctionId:
4971 break;
4972
4973 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00004974 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00004975 // C++0x inherited constructors.
4976 if (getLangOptions().CPlusPlus0x) break;
4977
Douglas Gregor12c118a2009-11-04 16:30:06 +00004978 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4979 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004980 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004981
4982 case UnqualifiedId::IK_DestructorName:
4983 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4984 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004985 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004986
4987 case UnqualifiedId::IK_TemplateId:
4988 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4989 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00004990 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004991 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004992
4993 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4994 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00004995 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00004996 return 0;
John McCall604e7f12009-12-08 07:46:18 +00004997
John McCall60fa3cf2009-12-11 02:10:03 +00004998 // Warn about using declarations.
4999 // TODO: store that the declaration was written without 'using' and
5000 // talk about access decls instead of using decls in the
5001 // diagnostics.
5002 if (!HasUsingKeyword) {
5003 UsingLoc = Name.getSourceRange().getBegin();
5004
5005 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005006 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005007 }
5008
Douglas Gregor56c04582010-12-16 00:46:58 +00005009 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5010 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5011 return 0;
5012
John McCall9488ea12009-11-17 05:59:44 +00005013 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005014 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005015 /* IsInstantiation */ false,
5016 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005017 if (UD)
5018 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005019
John McCalld226f652010-08-21 09:40:31 +00005020 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005021}
5022
Douglas Gregor09acc982010-07-07 23:08:52 +00005023/// \brief Determine whether a using declaration considers the given
5024/// declarations as "equivalent", e.g., if they are redeclarations of
5025/// the same entity or are both typedefs of the same type.
5026static bool
5027IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5028 bool &SuppressRedeclaration) {
5029 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5030 SuppressRedeclaration = false;
5031 return true;
5032 }
5033
Richard Smith162e1c12011-04-15 14:24:37 +00005034 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5035 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005036 SuppressRedeclaration = true;
5037 return Context.hasSameType(TD1->getUnderlyingType(),
5038 TD2->getUnderlyingType());
5039 }
5040
5041 return false;
5042}
5043
5044
John McCall9f54ad42009-12-10 09:41:52 +00005045/// Determines whether to create a using shadow decl for a particular
5046/// decl, given the set of decls existing prior to this using lookup.
5047bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5048 const LookupResult &Previous) {
5049 // Diagnose finding a decl which is not from a base class of the
5050 // current class. We do this now because there are cases where this
5051 // function will silently decide not to build a shadow decl, which
5052 // will pre-empt further diagnostics.
5053 //
5054 // We don't need to do this in C++0x because we do the check once on
5055 // the qualifier.
5056 //
5057 // FIXME: diagnose the following if we care enough:
5058 // struct A { int foo; };
5059 // struct B : A { using A::foo; };
5060 // template <class T> struct C : A {};
5061 // template <class T> struct D : C<T> { using B::foo; } // <---
5062 // This is invalid (during instantiation) in C++03 because B::foo
5063 // resolves to the using decl in B, which is not a base class of D<T>.
5064 // We can't diagnose it immediately because C<T> is an unknown
5065 // specialization. The UsingShadowDecl in D<T> then points directly
5066 // to A::foo, which will look well-formed when we instantiate.
5067 // The right solution is to not collapse the shadow-decl chain.
5068 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5069 DeclContext *OrigDC = Orig->getDeclContext();
5070
5071 // Handle enums and anonymous structs.
5072 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5073 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5074 while (OrigRec->isAnonymousStructOrUnion())
5075 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5076
5077 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5078 if (OrigDC == CurContext) {
5079 Diag(Using->getLocation(),
5080 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005081 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005082 Diag(Orig->getLocation(), diag::note_using_decl_target);
5083 return true;
5084 }
5085
Douglas Gregordc355712011-02-25 00:36:19 +00005086 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005087 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005088 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005089 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005090 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005091 Diag(Orig->getLocation(), diag::note_using_decl_target);
5092 return true;
5093 }
5094 }
5095
5096 if (Previous.empty()) return false;
5097
5098 NamedDecl *Target = Orig;
5099 if (isa<UsingShadowDecl>(Target))
5100 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5101
John McCalld7533ec2009-12-11 02:33:26 +00005102 // If the target happens to be one of the previous declarations, we
5103 // don't have a conflict.
5104 //
5105 // FIXME: but we might be increasing its access, in which case we
5106 // should redeclare it.
5107 NamedDecl *NonTag = 0, *Tag = 0;
5108 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5109 I != E; ++I) {
5110 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005111 bool Result;
5112 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5113 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005114
5115 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5116 }
5117
John McCall9f54ad42009-12-10 09:41:52 +00005118 if (Target->isFunctionOrFunctionTemplate()) {
5119 FunctionDecl *FD;
5120 if (isa<FunctionTemplateDecl>(Target))
5121 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5122 else
5123 FD = cast<FunctionDecl>(Target);
5124
5125 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005126 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005127 case Ovl_Overload:
5128 return false;
5129
5130 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005131 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005132 break;
5133
5134 // We found a decl with the exact signature.
5135 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005136 // If we're in a record, we want to hide the target, so we
5137 // return true (without a diagnostic) to tell the caller not to
5138 // build a shadow decl.
5139 if (CurContext->isRecord())
5140 return true;
5141
5142 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005143 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005144 break;
5145 }
5146
5147 Diag(Target->getLocation(), diag::note_using_decl_target);
5148 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5149 return true;
5150 }
5151
5152 // Target is not a function.
5153
John McCall9f54ad42009-12-10 09:41:52 +00005154 if (isa<TagDecl>(Target)) {
5155 // No conflict between a tag and a non-tag.
5156 if (!Tag) return false;
5157
John McCall41ce66f2009-12-10 19:51:03 +00005158 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005159 Diag(Target->getLocation(), diag::note_using_decl_target);
5160 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5161 return true;
5162 }
5163
5164 // No conflict between a tag and a non-tag.
5165 if (!NonTag) return false;
5166
John McCall41ce66f2009-12-10 19:51:03 +00005167 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005168 Diag(Target->getLocation(), diag::note_using_decl_target);
5169 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5170 return true;
5171}
5172
John McCall9488ea12009-11-17 05:59:44 +00005173/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005174UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005175 UsingDecl *UD,
5176 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005177
5178 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005179 NamedDecl *Target = Orig;
5180 if (isa<UsingShadowDecl>(Target)) {
5181 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5182 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005183 }
5184
5185 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005186 = UsingShadowDecl::Create(Context, CurContext,
5187 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005188 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005189
5190 Shadow->setAccess(UD->getAccess());
5191 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5192 Shadow->setInvalidDecl();
5193
John McCall9488ea12009-11-17 05:59:44 +00005194 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005195 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005196 else
John McCall604e7f12009-12-08 07:46:18 +00005197 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005198
John McCall604e7f12009-12-08 07:46:18 +00005199
John McCall9f54ad42009-12-10 09:41:52 +00005200 return Shadow;
5201}
John McCall604e7f12009-12-08 07:46:18 +00005202
John McCall9f54ad42009-12-10 09:41:52 +00005203/// Hides a using shadow declaration. This is required by the current
5204/// using-decl implementation when a resolvable using declaration in a
5205/// class is followed by a declaration which would hide or override
5206/// one or more of the using decl's targets; for example:
5207///
5208/// struct Base { void foo(int); };
5209/// struct Derived : Base {
5210/// using Base::foo;
5211/// void foo(int);
5212/// };
5213///
5214/// The governing language is C++03 [namespace.udecl]p12:
5215///
5216/// When a using-declaration brings names from a base class into a
5217/// derived class scope, member functions in the derived class
5218/// override and/or hide member functions with the same name and
5219/// parameter types in a base class (rather than conflicting).
5220///
5221/// There are two ways to implement this:
5222/// (1) optimistically create shadow decls when they're not hidden
5223/// by existing declarations, or
5224/// (2) don't create any shadow decls (or at least don't make them
5225/// visible) until we've fully parsed/instantiated the class.
5226/// The problem with (1) is that we might have to retroactively remove
5227/// a shadow decl, which requires several O(n) operations because the
5228/// decl structures are (very reasonably) not designed for removal.
5229/// (2) avoids this but is very fiddly and phase-dependent.
5230void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005231 if (Shadow->getDeclName().getNameKind() ==
5232 DeclarationName::CXXConversionFunctionName)
5233 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5234
John McCall9f54ad42009-12-10 09:41:52 +00005235 // Remove it from the DeclContext...
5236 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005237
John McCall9f54ad42009-12-10 09:41:52 +00005238 // ...and the scope, if applicable...
5239 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005240 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005241 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005242 }
5243
John McCall9f54ad42009-12-10 09:41:52 +00005244 // ...and the using decl.
5245 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5246
5247 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005248 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005249}
5250
John McCall7ba107a2009-11-18 02:36:19 +00005251/// Builds a using declaration.
5252///
5253/// \param IsInstantiation - Whether this call arises from an
5254/// instantiation of an unresolved using declaration. We treat
5255/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005256NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5257 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005258 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005259 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005260 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005261 bool IsInstantiation,
5262 bool IsTypeName,
5263 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005264 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005265 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005266 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005267
Anders Carlsson550b14b2009-08-28 05:49:21 +00005268 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005269
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005270 if (SS.isEmpty()) {
5271 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005272 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274
John McCall9f54ad42009-12-10 09:41:52 +00005275 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005276 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005277 ForRedeclaration);
5278 Previous.setHideTags(false);
5279 if (S) {
5280 LookupName(Previous, S);
5281
5282 // It is really dumb that we have to do this.
5283 LookupResult::Filter F = Previous.makeFilter();
5284 while (F.hasNext()) {
5285 NamedDecl *D = F.next();
5286 if (!isDeclInScope(D, CurContext, S))
5287 F.erase();
5288 }
5289 F.done();
5290 } else {
5291 assert(IsInstantiation && "no scope in non-instantiation");
5292 assert(CurContext->isRecord() && "scope not record in instantiation");
5293 LookupQualifiedName(Previous, CurContext);
5294 }
5295
John McCall9f54ad42009-12-10 09:41:52 +00005296 // Check for invalid redeclarations.
5297 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5298 return 0;
5299
5300 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005301 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5302 return 0;
5303
John McCallaf8e6ed2009-11-12 03:15:40 +00005304 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005305 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005306 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005307 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005308 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005309 // FIXME: not all declaration name kinds are legal here
5310 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5311 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005312 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005313 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005314 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005315 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5316 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005317 }
John McCalled976492009-12-04 22:46:56 +00005318 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005319 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5320 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005321 }
John McCalled976492009-12-04 22:46:56 +00005322 D->setAccess(AS);
5323 CurContext->addDecl(D);
5324
5325 if (!LookupContext) return D;
5326 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005327
John McCall77bb1aa2010-05-01 00:40:08 +00005328 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005329 UD->setInvalidDecl();
5330 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005331 }
5332
Sebastian Redlf677ea32011-02-05 19:23:19 +00005333 // Constructor inheriting using decls get special treatment.
5334 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005335 if (CheckInheritedConstructorUsingDecl(UD))
5336 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005337 return UD;
5338 }
5339
5340 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005341
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005342 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00005343
John McCall604e7f12009-12-08 07:46:18 +00005344 // Unlike most lookups, we don't always want to hide tag
5345 // declarations: tag names are visible through the using declaration
5346 // even if hidden by ordinary names, *except* in a dependent context
5347 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005348 if (!IsInstantiation)
5349 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005350
John McCalla24dc2e2009-11-17 02:14:36 +00005351 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005352
John McCallf36e02d2009-10-09 21:13:30 +00005353 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005354 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005355 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005356 UD->setInvalidDecl();
5357 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005358 }
5359
John McCalled976492009-12-04 22:46:56 +00005360 if (R.isAmbiguous()) {
5361 UD->setInvalidDecl();
5362 return UD;
5363 }
Mike Stump1eb44332009-09-09 15:08:12 +00005364
John McCall7ba107a2009-11-18 02:36:19 +00005365 if (IsTypeName) {
5366 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005367 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005368 Diag(IdentLoc, diag::err_using_typename_non_type);
5369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5370 Diag((*I)->getUnderlyingDecl()->getLocation(),
5371 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005372 UD->setInvalidDecl();
5373 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005374 }
5375 } else {
5376 // If we asked for a non-typename and we got a type, error out,
5377 // but only if this is an instantiation of an unresolved using
5378 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005379 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005380 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5381 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005382 UD->setInvalidDecl();
5383 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005384 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005385 }
5386
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005387 // C++0x N2914 [namespace.udecl]p6:
5388 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005389 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005390 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5391 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005392 UD->setInvalidDecl();
5393 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005394 }
Mike Stump1eb44332009-09-09 15:08:12 +00005395
John McCall9f54ad42009-12-10 09:41:52 +00005396 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5397 if (!CheckUsingShadowDecl(UD, *I, Previous))
5398 BuildUsingShadowDecl(S, UD, *I);
5399 }
John McCall9488ea12009-11-17 05:59:44 +00005400
5401 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005402}
5403
Sebastian Redlf677ea32011-02-05 19:23:19 +00005404/// Additional checks for a using declaration referring to a constructor name.
5405bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5406 if (UD->isTypeName()) {
5407 // FIXME: Cannot specify typename when specifying constructor
5408 return true;
5409 }
5410
Douglas Gregordc355712011-02-25 00:36:19 +00005411 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005412 assert(SourceType &&
5413 "Using decl naming constructor doesn't have type in scope spec.");
5414 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5415
5416 // Check whether the named type is a direct base class.
5417 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5418 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5419 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5420 BaseIt != BaseE; ++BaseIt) {
5421 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5422 if (CanonicalSourceType == BaseType)
5423 break;
5424 }
5425
5426 if (BaseIt == BaseE) {
5427 // Did not find SourceType in the bases.
5428 Diag(UD->getUsingLocation(),
5429 diag::err_using_decl_constructor_not_in_direct_base)
5430 << UD->getNameInfo().getSourceRange()
5431 << QualType(SourceType, 0) << TargetClass;
5432 return true;
5433 }
5434
5435 BaseIt->setInheritConstructors();
5436
5437 return false;
5438}
5439
John McCall9f54ad42009-12-10 09:41:52 +00005440/// Checks that the given using declaration is not an invalid
5441/// redeclaration. Note that this is checking only for the using decl
5442/// itself, not for any ill-formedness among the UsingShadowDecls.
5443bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5444 bool isTypeName,
5445 const CXXScopeSpec &SS,
5446 SourceLocation NameLoc,
5447 const LookupResult &Prev) {
5448 // C++03 [namespace.udecl]p8:
5449 // C++0x [namespace.udecl]p10:
5450 // A using-declaration is a declaration and can therefore be used
5451 // repeatedly where (and only where) multiple declarations are
5452 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00005453 //
John McCall8a726212010-11-29 18:01:58 +00005454 // That's in non-member contexts.
5455 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00005456 return false;
5457
5458 NestedNameSpecifier *Qual
5459 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5460
5461 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5462 NamedDecl *D = *I;
5463
5464 bool DTypename;
5465 NestedNameSpecifier *DQual;
5466 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5467 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00005468 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005469 } else if (UnresolvedUsingValueDecl *UD
5470 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5471 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00005472 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005473 } else if (UnresolvedUsingTypenameDecl *UD
5474 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5475 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00005476 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005477 } else continue;
5478
5479 // using decls differ if one says 'typename' and the other doesn't.
5480 // FIXME: non-dependent using decls?
5481 if (isTypeName != DTypename) continue;
5482
5483 // using decls differ if they name different scopes (but note that
5484 // template instantiation can cause this check to trigger when it
5485 // didn't before instantiation).
5486 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5487 Context.getCanonicalNestedNameSpecifier(DQual))
5488 continue;
5489
5490 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00005491 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00005492 return true;
5493 }
5494
5495 return false;
5496}
5497
John McCall604e7f12009-12-08 07:46:18 +00005498
John McCalled976492009-12-04 22:46:56 +00005499/// Checks that the given nested-name qualifier used in a using decl
5500/// in the current context is appropriately related to the current
5501/// scope. If an error is found, diagnoses it and returns true.
5502bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5503 const CXXScopeSpec &SS,
5504 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00005505 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005506
John McCall604e7f12009-12-08 07:46:18 +00005507 if (!CurContext->isRecord()) {
5508 // C++03 [namespace.udecl]p3:
5509 // C++0x [namespace.udecl]p8:
5510 // A using-declaration for a class member shall be a member-declaration.
5511
5512 // If we weren't able to compute a valid scope, it must be a
5513 // dependent class scope.
5514 if (!NamedContext || NamedContext->isRecord()) {
5515 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5516 << SS.getRange();
5517 return true;
5518 }
5519
5520 // Otherwise, everything is known to be fine.
5521 return false;
5522 }
5523
5524 // The current scope is a record.
5525
5526 // If the named context is dependent, we can't decide much.
5527 if (!NamedContext) {
5528 // FIXME: in C++0x, we can diagnose if we can prove that the
5529 // nested-name-specifier does not refer to a base class, which is
5530 // still possible in some cases.
5531
5532 // Otherwise we have to conservatively report that things might be
5533 // okay.
5534 return false;
5535 }
5536
5537 if (!NamedContext->isRecord()) {
5538 // Ideally this would point at the last name in the specifier,
5539 // but we don't have that level of source info.
5540 Diag(SS.getRange().getBegin(),
5541 diag::err_using_decl_nested_name_specifier_is_not_class)
5542 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5543 return true;
5544 }
5545
Douglas Gregor6fb07292010-12-21 07:41:49 +00005546 if (!NamedContext->isDependentContext() &&
5547 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5548 return true;
5549
John McCall604e7f12009-12-08 07:46:18 +00005550 if (getLangOptions().CPlusPlus0x) {
5551 // C++0x [namespace.udecl]p3:
5552 // In a using-declaration used as a member-declaration, the
5553 // nested-name-specifier shall name a base class of the class
5554 // being defined.
5555
5556 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5557 cast<CXXRecordDecl>(NamedContext))) {
5558 if (CurContext == NamedContext) {
5559 Diag(NameLoc,
5560 diag::err_using_decl_nested_name_specifier_is_current_class)
5561 << SS.getRange();
5562 return true;
5563 }
5564
5565 Diag(SS.getRange().getBegin(),
5566 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5567 << (NestedNameSpecifier*) SS.getScopeRep()
5568 << cast<CXXRecordDecl>(CurContext)
5569 << SS.getRange();
5570 return true;
5571 }
5572
5573 return false;
5574 }
5575
5576 // C++03 [namespace.udecl]p4:
5577 // A using-declaration used as a member-declaration shall refer
5578 // to a member of a base class of the class being defined [etc.].
5579
5580 // Salient point: SS doesn't have to name a base class as long as
5581 // lookup only finds members from base classes. Therefore we can
5582 // diagnose here only if we can prove that that can't happen,
5583 // i.e. if the class hierarchies provably don't intersect.
5584
5585 // TODO: it would be nice if "definitely valid" results were cached
5586 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5587 // need to be repeated.
5588
5589 struct UserData {
5590 llvm::DenseSet<const CXXRecordDecl*> Bases;
5591
5592 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5593 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5594 Data->Bases.insert(Base);
5595 return true;
5596 }
5597
5598 bool hasDependentBases(const CXXRecordDecl *Class) {
5599 return !Class->forallBases(collect, this);
5600 }
5601
5602 /// Returns true if the base is dependent or is one of the
5603 /// accumulated base classes.
5604 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5605 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5606 return !Data->Bases.count(Base);
5607 }
5608
5609 bool mightShareBases(const CXXRecordDecl *Class) {
5610 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5611 }
5612 };
5613
5614 UserData Data;
5615
5616 // Returns false if we find a dependent base.
5617 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5618 return false;
5619
5620 // Returns false if the class has a dependent base or if it or one
5621 // of its bases is present in the base set of the current context.
5622 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5623 return false;
5624
5625 Diag(SS.getRange().getBegin(),
5626 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5627 << (NestedNameSpecifier*) SS.getScopeRep()
5628 << cast<CXXRecordDecl>(CurContext)
5629 << SS.getRange();
5630
5631 return true;
John McCalled976492009-12-04 22:46:56 +00005632}
5633
Richard Smith162e1c12011-04-15 14:24:37 +00005634Decl *Sema::ActOnAliasDeclaration(Scope *S,
5635 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005636 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00005637 SourceLocation UsingLoc,
5638 UnqualifiedId &Name,
5639 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00005640 // Skip up to the relevant declaration scope.
5641 while (S->getFlags() & Scope::TemplateParamScope)
5642 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00005643 assert((S->getFlags() & Scope::DeclScope) &&
5644 "got alias-declaration outside of declaration scope");
5645
5646 if (Type.isInvalid())
5647 return 0;
5648
5649 bool Invalid = false;
5650 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5651 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00005652 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00005653
5654 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5655 return 0;
5656
5657 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005658 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00005659 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005660 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5661 TInfo->getTypeLoc().getBeginLoc());
5662 }
Richard Smith162e1c12011-04-15 14:24:37 +00005663
5664 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5665 LookupName(Previous, S);
5666
5667 // Warn about shadowing the name of a template parameter.
5668 if (Previous.isSingleResult() &&
5669 Previous.getFoundDecl()->isTemplateParameter()) {
5670 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5671 Previous.getFoundDecl()))
5672 Invalid = true;
5673 Previous.clear();
5674 }
5675
5676 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5677 "name in alias declaration must be an identifier");
5678 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5679 Name.StartLocation,
5680 Name.Identifier, TInfo);
5681
5682 NewTD->setAccess(AS);
5683
5684 if (Invalid)
5685 NewTD->setInvalidDecl();
5686
Richard Smith3e4c6c42011-05-05 21:57:07 +00005687 CheckTypedefForVariablyModifiedType(S, NewTD);
5688 Invalid |= NewTD->isInvalidDecl();
5689
Richard Smith162e1c12011-04-15 14:24:37 +00005690 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005691
5692 NamedDecl *NewND;
5693 if (TemplateParamLists.size()) {
5694 TypeAliasTemplateDecl *OldDecl = 0;
5695 TemplateParameterList *OldTemplateParams = 0;
5696
5697 if (TemplateParamLists.size() != 1) {
5698 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5699 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5700 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5701 }
5702 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5703
5704 // Only consider previous declarations in the same scope.
5705 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5706 /*ExplicitInstantiationOrSpecialization*/false);
5707 if (!Previous.empty()) {
5708 Redeclaration = true;
5709
5710 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5711 if (!OldDecl && !Invalid) {
5712 Diag(UsingLoc, diag::err_redefinition_different_kind)
5713 << Name.Identifier;
5714
5715 NamedDecl *OldD = Previous.getRepresentativeDecl();
5716 if (OldD->getLocation().isValid())
5717 Diag(OldD->getLocation(), diag::note_previous_definition);
5718
5719 Invalid = true;
5720 }
5721
5722 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5723 if (TemplateParameterListsAreEqual(TemplateParams,
5724 OldDecl->getTemplateParameters(),
5725 /*Complain=*/true,
5726 TPL_TemplateMatch))
5727 OldTemplateParams = OldDecl->getTemplateParameters();
5728 else
5729 Invalid = true;
5730
5731 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5732 if (!Invalid &&
5733 !Context.hasSameType(OldTD->getUnderlyingType(),
5734 NewTD->getUnderlyingType())) {
5735 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5736 // but we can't reasonably accept it.
5737 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5738 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5739 if (OldTD->getLocation().isValid())
5740 Diag(OldTD->getLocation(), diag::note_previous_definition);
5741 Invalid = true;
5742 }
5743 }
5744 }
5745
5746 // Merge any previous default template arguments into our parameters,
5747 // and check the parameter list.
5748 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5749 TPC_TypeAliasTemplate))
5750 return 0;
5751
5752 TypeAliasTemplateDecl *NewDecl =
5753 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5754 Name.Identifier, TemplateParams,
5755 NewTD);
5756
5757 NewDecl->setAccess(AS);
5758
5759 if (Invalid)
5760 NewDecl->setInvalidDecl();
5761 else if (OldDecl)
5762 NewDecl->setPreviousDeclaration(OldDecl);
5763
5764 NewND = NewDecl;
5765 } else {
5766 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5767 NewND = NewTD;
5768 }
Richard Smith162e1c12011-04-15 14:24:37 +00005769
5770 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00005771 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00005772
Richard Smith3e4c6c42011-05-05 21:57:07 +00005773 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00005774}
5775
John McCalld226f652010-08-21 09:40:31 +00005776Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005777 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005778 SourceLocation AliasLoc,
5779 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005780 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005781 SourceLocation IdentLoc,
5782 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00005783
Anders Carlsson81c85c42009-03-28 23:53:49 +00005784 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005785 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5786 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00005787
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005788 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00005789 NamedDecl *PrevDecl
5790 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5791 ForRedeclaration);
5792 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5793 PrevDecl = 0;
5794
5795 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00005796 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005797 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00005798 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00005799 // FIXME: At some point, we'll want to create the (redundant)
5800 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00005801 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00005802 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00005803 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00005804 }
Mike Stump1eb44332009-09-09 15:08:12 +00005805
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005806 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5807 diag::err_redefinition_different_kind;
5808 Diag(AliasLoc, DiagID) << Alias;
5809 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00005810 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005811 }
5812
John McCalla24dc2e2009-11-17 02:14:36 +00005813 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005814 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005815
John McCallf36e02d2009-10-09 21:13:30 +00005816 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005817 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5818 CTC_NoKeywords, 0)) {
5819 if (R.getAsSingle<NamespaceDecl>() ||
5820 R.getAsSingle<NamespaceAliasDecl>()) {
5821 if (DeclContext *DC = computeDeclContext(SS, false))
5822 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5823 << Ident << DC << Corrected << SS.getRange()
5824 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5825 else
5826 Diag(IdentLoc, diag::err_using_directive_suggest)
5827 << Ident << Corrected
5828 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5829
5830 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5831 << Corrected;
5832
5833 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00005834 } else {
5835 R.clear();
5836 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005837 }
5838 }
5839
5840 if (R.empty()) {
5841 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005842 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005843 }
Anders Carlsson5721c682009-03-28 06:42:02 +00005844 }
Mike Stump1eb44332009-09-09 15:08:12 +00005845
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005846 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00005847 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00005848 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00005849 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00005850
John McCall3dbd3d52010-02-16 06:53:13 +00005851 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00005852 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00005853}
5854
Douglas Gregor39957dc2010-05-01 15:04:51 +00005855namespace {
5856 /// \brief Scoped object used to handle the state changes required in Sema
5857 /// to implicitly define the body of a C++ member function;
5858 class ImplicitlyDefinedFunctionScope {
5859 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00005860 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00005861
5862 public:
5863 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00005864 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00005865 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00005866 S.PushFunctionScope();
5867 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5868 }
5869
5870 ~ImplicitlyDefinedFunctionScope() {
5871 S.PopExpressionEvaluationContext();
5872 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00005873 }
5874 };
5875}
5876
Sebastian Redl751025d2010-09-13 22:02:47 +00005877static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
5878 CXXRecordDecl *D) {
5879 ASTContext &Context = Self.Context;
5880 QualType ClassType = Context.getTypeDeclType(D);
5881 DeclarationName ConstructorName
5882 = Context.DeclarationNames.getCXXConstructorName(
5883 Context.getCanonicalType(ClassType.getUnqualifiedType()));
5884
5885 DeclContext::lookup_const_iterator Con, ConEnd;
5886 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
5887 Con != ConEnd; ++Con) {
5888 // FIXME: In C++0x, a constructor template can be a default constructor.
5889 if (isa<FunctionTemplateDecl>(*Con))
5890 continue;
5891
5892 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
5893 if (Constructor->isDefaultConstructor())
5894 return Constructor;
5895 }
5896 return 0;
5897}
5898
Sean Hunt001cad92011-05-10 00:49:42 +00005899Sema::ImplicitExceptionSpecification
5900Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005901 // C++ [except.spec]p14:
5902 // An implicitly declared special member function (Clause 12) shall have an
5903 // exception-specification. [...]
5904 ImplicitExceptionSpecification ExceptSpec(Context);
5905
Sebastian Redl60618fa2011-03-12 11:50:43 +00005906 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005907 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5908 BEnd = ClassDecl->bases_end();
5909 B != BEnd; ++B) {
5910 if (B->isVirtual()) // Handled below.
5911 continue;
5912
Douglas Gregor18274032010-07-03 00:47:00 +00005913 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5914 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntcdee3fe2011-05-11 22:34:38 +00005915 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005916 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00005917 else if (CXXConstructorDecl *Constructor
5918 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005919 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005920 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005921 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005922
5923 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005924 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5925 BEnd = ClassDecl->vbases_end();
5926 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00005927 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5928 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntcdee3fe2011-05-11 22:34:38 +00005929 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005930 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5931 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005932 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005933 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005934 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005935 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005936
5937 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005938 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5939 FEnd = ClassDecl->field_end();
5940 F != FEnd; ++F) {
5941 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00005942 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5943 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Sean Huntcdee3fe2011-05-11 22:34:38 +00005944 if (FieldClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005945 ExceptSpec.CalledDecl(
5946 DeclareImplicitDefaultConstructor(FieldClassDecl));
5947 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005948 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005949 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005950 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005951 }
John McCalle23cf432010-12-14 08:05:40 +00005952
Sean Hunt001cad92011-05-10 00:49:42 +00005953 return ExceptSpec;
5954}
5955
5956CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5957 CXXRecordDecl *ClassDecl) {
5958 // C++ [class.ctor]p5:
5959 // A default constructor for a class X is a constructor of class X
5960 // that can be called without an argument. If there is no
5961 // user-declared constructor for class X, a default constructor is
5962 // implicitly declared. An implicitly-declared default constructor
5963 // is an inline public member of its class.
5964 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5965 "Should not build implicit default constructor!");
5966
5967 ImplicitExceptionSpecification Spec =
5968 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5969 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00005970
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005971 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00005972 CanQualType ClassType
5973 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005974 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005975 DeclarationName Name
5976 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005977 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005978 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005979 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00005980 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005981 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00005982 /*TInfo=*/0,
5983 /*isExplicit=*/false,
5984 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005985 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005986 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00005987 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005988 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00005989 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00005990
5991 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00005992 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5993
Douglas Gregor23c94db2010-07-02 17:43:08 +00005994 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00005995 PushOnScopeChains(DefaultCon, S, false);
5996 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00005997
5998 if (ShouldDeleteDefaultConstructor(DefaultCon))
5999 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006000
Douglas Gregor32df23e2010-07-01 22:02:46 +00006001 return DefaultCon;
6002}
6003
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006004void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6005 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006006 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00006007 !Constructor->isUsed(false) && !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006008 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006009
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006010 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006011 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006012
Douglas Gregor39957dc2010-05-01 15:04:51 +00006013 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006014 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006015 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006016 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006017 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006018 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006019 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006020 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006021 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006022
6023 SourceLocation Loc = Constructor->getLocation();
6024 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6025
6026 Constructor->setUsed();
6027 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006028
6029 if (ASTMutationListener *L = getASTMutationListener()) {
6030 L->CompletedImplicitDefinition(Constructor);
6031 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006032}
6033
Sebastian Redlf677ea32011-02-05 19:23:19 +00006034void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6035 // We start with an initial pass over the base classes to collect those that
6036 // inherit constructors from. If there are none, we can forgo all further
6037 // processing.
6038 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6039 BasesVector BasesToInheritFrom;
6040 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6041 BaseE = ClassDecl->bases_end();
6042 BaseIt != BaseE; ++BaseIt) {
6043 if (BaseIt->getInheritConstructors()) {
6044 QualType Base = BaseIt->getType();
6045 if (Base->isDependentType()) {
6046 // If we inherit constructors from anything that is dependent, just
6047 // abort processing altogether. We'll get another chance for the
6048 // instantiations.
6049 return;
6050 }
6051 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6052 }
6053 }
6054 if (BasesToInheritFrom.empty())
6055 return;
6056
6057 // Now collect the constructors that we already have in the current class.
6058 // Those take precedence over inherited constructors.
6059 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6060 // unless there is a user-declared constructor with the same signature in
6061 // the class where the using-declaration appears.
6062 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6063 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6064 CtorE = ClassDecl->ctor_end();
6065 CtorIt != CtorE; ++CtorIt) {
6066 ExistingConstructors.insert(
6067 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6068 }
6069
6070 Scope *S = getScopeForContext(ClassDecl);
6071 DeclarationName CreatedCtorName =
6072 Context.DeclarationNames.getCXXConstructorName(
6073 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6074
6075 // Now comes the true work.
6076 // First, we keep a map from constructor types to the base that introduced
6077 // them. Needed for finding conflicting constructors. We also keep the
6078 // actually inserted declarations in there, for pretty diagnostics.
6079 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6080 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6081 ConstructorToSourceMap InheritedConstructors;
6082 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6083 BaseE = BasesToInheritFrom.end();
6084 BaseIt != BaseE; ++BaseIt) {
6085 const RecordType *Base = *BaseIt;
6086 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6087 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6088 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6089 CtorE = BaseDecl->ctor_end();
6090 CtorIt != CtorE; ++CtorIt) {
6091 // Find the using declaration for inheriting this base's constructors.
6092 DeclarationName Name =
6093 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6094 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6095 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6096 SourceLocation UsingLoc = UD ? UD->getLocation() :
6097 ClassDecl->getLocation();
6098
6099 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6100 // from the class X named in the using-declaration consists of actual
6101 // constructors and notional constructors that result from the
6102 // transformation of defaulted parameters as follows:
6103 // - all non-template default constructors of X, and
6104 // - for each non-template constructor of X that has at least one
6105 // parameter with a default argument, the set of constructors that
6106 // results from omitting any ellipsis parameter specification and
6107 // successively omitting parameters with a default argument from the
6108 // end of the parameter-type-list.
6109 CXXConstructorDecl *BaseCtor = *CtorIt;
6110 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6111 const FunctionProtoType *BaseCtorType =
6112 BaseCtor->getType()->getAs<FunctionProtoType>();
6113
6114 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6115 maxParams = BaseCtor->getNumParams();
6116 params <= maxParams; ++params) {
6117 // Skip default constructors. They're never inherited.
6118 if (params == 0)
6119 continue;
6120 // Skip copy and move constructors for the same reason.
6121 if (CanBeCopyOrMove && params == 1)
6122 continue;
6123
6124 // Build up a function type for this particular constructor.
6125 // FIXME: The working paper does not consider that the exception spec
6126 // for the inheriting constructor might be larger than that of the
6127 // source. This code doesn't yet, either.
6128 const Type *NewCtorType;
6129 if (params == maxParams)
6130 NewCtorType = BaseCtorType;
6131 else {
6132 llvm::SmallVector<QualType, 16> Args;
6133 for (unsigned i = 0; i < params; ++i) {
6134 Args.push_back(BaseCtorType->getArgType(i));
6135 }
6136 FunctionProtoType::ExtProtoInfo ExtInfo =
6137 BaseCtorType->getExtProtoInfo();
6138 ExtInfo.Variadic = false;
6139 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6140 Args.data(), params, ExtInfo)
6141 .getTypePtr();
6142 }
6143 const Type *CanonicalNewCtorType =
6144 Context.getCanonicalType(NewCtorType);
6145
6146 // Now that we have the type, first check if the class already has a
6147 // constructor with this signature.
6148 if (ExistingConstructors.count(CanonicalNewCtorType))
6149 continue;
6150
6151 // Then we check if we have already declared an inherited constructor
6152 // with this signature.
6153 std::pair<ConstructorToSourceMap::iterator, bool> result =
6154 InheritedConstructors.insert(std::make_pair(
6155 CanonicalNewCtorType,
6156 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6157 if (!result.second) {
6158 // Already in the map. If it came from a different class, that's an
6159 // error. Not if it's from the same.
6160 CanQualType PreviousBase = result.first->second.first;
6161 if (CanonicalBase != PreviousBase) {
6162 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6163 const CXXConstructorDecl *PrevBaseCtor =
6164 PrevCtor->getInheritedConstructor();
6165 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6166
6167 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6168 Diag(BaseCtor->getLocation(),
6169 diag::note_using_decl_constructor_conflict_current_ctor);
6170 Diag(PrevBaseCtor->getLocation(),
6171 diag::note_using_decl_constructor_conflict_previous_ctor);
6172 Diag(PrevCtor->getLocation(),
6173 diag::note_using_decl_constructor_conflict_previous_using);
6174 }
6175 continue;
6176 }
6177
6178 // OK, we're there, now add the constructor.
6179 // C++0x [class.inhctor]p8: [...] that would be performed by a
6180 // user-writtern inline constructor [...]
6181 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6182 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006183 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6184 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006185 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006186 NewCtor->setAccess(BaseCtor->getAccess());
6187
6188 // Build up the parameter decls and add them.
6189 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6190 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006191 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6192 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006193 /*IdentifierInfo=*/0,
6194 BaseCtorType->getArgType(i),
6195 /*TInfo=*/0, SC_None,
6196 SC_None, /*DefaultArg=*/0));
6197 }
6198 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6199 NewCtor->setInheritedConstructor(BaseCtor);
6200
6201 PushOnScopeChains(NewCtor, S, false);
6202 ClassDecl->addDecl(NewCtor);
6203 result.first->second.second = NewCtor;
6204 }
6205 }
6206 }
6207}
6208
Sean Huntcb45a0f2011-05-12 22:46:25 +00006209Sema::ImplicitExceptionSpecification
6210Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006211 // C++ [except.spec]p14:
6212 // An implicitly declared special member function (Clause 12) shall have
6213 // an exception-specification.
6214 ImplicitExceptionSpecification ExceptSpec(Context);
6215
6216 // Direct base-class destructors.
6217 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6218 BEnd = ClassDecl->bases_end();
6219 B != BEnd; ++B) {
6220 if (B->isVirtual()) // Handled below.
6221 continue;
6222
6223 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6224 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00006225 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006226 }
6227
6228 // Virtual base-class destructors.
6229 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6230 BEnd = ClassDecl->vbases_end();
6231 B != BEnd; ++B) {
6232 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6233 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00006234 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006235 }
6236
6237 // Field destructors.
6238 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6239 FEnd = ClassDecl->field_end();
6240 F != FEnd; ++F) {
6241 if (const RecordType *RecordTy
6242 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6243 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00006244 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006245 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006246
Sean Huntcb45a0f2011-05-12 22:46:25 +00006247 return ExceptSpec;
6248}
6249
6250CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6251 // C++ [class.dtor]p2:
6252 // If a class has no user-declared destructor, a destructor is
6253 // declared implicitly. An implicitly-declared destructor is an
6254 // inline public member of its class.
6255
6256 ImplicitExceptionSpecification Spec =
6257 ComputeDefaultedDtorExceptionSpec(ClassDecl);
6258 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6259
Douglas Gregor4923aa22010-07-02 20:37:36 +00006260 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006261 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006262
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006263 CanQualType ClassType
6264 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006265 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006266 DeclarationName Name
6267 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006268 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006269 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006270 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6271 /*isInline=*/true,
6272 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006273 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006274 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006275 Destructor->setImplicit();
6276 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006277
6278 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006279 ++ASTContext::NumImplicitDestructorsDeclared;
6280
6281 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006282 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006283 PushOnScopeChains(Destructor, S, false);
6284 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006285
6286 // This could be uniqued if it ever proves significant.
6287 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006288
6289 if (ShouldDeleteDestructor(Destructor))
6290 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006291
6292 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006293
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006294 return Destructor;
6295}
6296
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006297void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006298 CXXDestructorDecl *Destructor) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00006299 assert((Destructor->isDefaulted() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006300 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006301 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006302 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006303
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006304 if (Destructor->isInvalidDecl())
6305 return;
6306
Douglas Gregor39957dc2010-05-01 15:04:51 +00006307 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006308
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006309 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006310 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6311 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006312
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006313 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006314 Diag(CurrentLocation, diag::note_member_synthesized_at)
6315 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6316
6317 Destructor->setInvalidDecl();
6318 return;
6319 }
6320
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006321 SourceLocation Loc = Destructor->getLocation();
6322 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6323
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006324 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006325 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006326
6327 if (ASTMutationListener *L = getASTMutationListener()) {
6328 L->CompletedImplicitDefinition(Destructor);
6329 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006330}
6331
Douglas Gregor06a9f362010-05-01 20:49:11 +00006332/// \brief Builds a statement that copies the given entity from \p From to
6333/// \c To.
6334///
6335/// This routine is used to copy the members of a class with an
6336/// implicitly-declared copy assignment operator. When the entities being
6337/// copied are arrays, this routine builds for loops to copy them.
6338///
6339/// \param S The Sema object used for type-checking.
6340///
6341/// \param Loc The location where the implicit copy is being generated.
6342///
6343/// \param T The type of the expressions being copied. Both expressions must
6344/// have this type.
6345///
6346/// \param To The expression we are copying to.
6347///
6348/// \param From The expression we are copying from.
6349///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006350/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6351/// Otherwise, it's a non-static member subobject.
6352///
Douglas Gregor06a9f362010-05-01 20:49:11 +00006353/// \param Depth Internal parameter recording the depth of the recursion.
6354///
6355/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006356static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00006357BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00006358 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006359 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006360 // C++0x [class.copy]p30:
6361 // Each subobject is assigned in the manner appropriate to its type:
6362 //
6363 // - if the subobject is of class type, the copy assignment operator
6364 // for the class is used (as if by explicit qualification; that is,
6365 // ignoring any possible virtual overriding functions in more derived
6366 // classes);
6367 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6368 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6369
6370 // Look for operator=.
6371 DeclarationName Name
6372 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6373 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6374 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6375
6376 // Filter out any result that isn't a copy-assignment operator.
6377 LookupResult::Filter F = OpLookup.makeFilter();
6378 while (F.hasNext()) {
6379 NamedDecl *D = F.next();
6380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6381 if (Method->isCopyAssignmentOperator())
6382 continue;
6383
6384 F.erase();
John McCallb0207482010-03-16 06:11:48 +00006385 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006386 F.done();
6387
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006388 // Suppress the protected check (C++ [class.protected]) for each of the
6389 // assignment operators we found. This strange dance is required when
6390 // we're assigning via a base classes's copy-assignment operator. To
6391 // ensure that we're getting the right base class subobject (without
6392 // ambiguities), we need to cast "this" to that subobject type; to
6393 // ensure that we don't go through the virtual call mechanism, we need
6394 // to qualify the operator= name with the base class (see below). However,
6395 // this means that if the base class has a protected copy assignment
6396 // operator, the protected member access check will fail. So, we
6397 // rewrite "protected" access to "public" access in this case, since we
6398 // know by construction that we're calling from a derived class.
6399 if (CopyingBaseSubobject) {
6400 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6401 L != LEnd; ++L) {
6402 if (L.getAccess() == AS_protected)
6403 L.setAccess(AS_public);
6404 }
6405 }
6406
Douglas Gregor06a9f362010-05-01 20:49:11 +00006407 // Create the nested-name-specifier that will be used to qualify the
6408 // reference to operator=; this is required to suppress the virtual
6409 // call mechanism.
6410 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00006411 SS.MakeTrivial(S.Context,
6412 NestedNameSpecifier::Create(S.Context, 0, false,
6413 T.getTypePtr()),
6414 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006415
6416 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00006417 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00006418 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006419 /*FirstQualifierInScope=*/0, OpLookup,
6420 /*TemplateArgs=*/0,
6421 /*SuppressQualifierCheck=*/true);
6422 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006423 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006424
6425 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00006426
John McCall60d7b3a2010-08-24 06:29:42 +00006427 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00006428 OpEqualRef.takeAs<Expr>(),
6429 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006430 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006431 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006432
6433 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006434 }
John McCallb0207482010-03-16 06:11:48 +00006435
Douglas Gregor06a9f362010-05-01 20:49:11 +00006436 // - if the subobject is of scalar type, the built-in assignment
6437 // operator is used.
6438 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6439 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00006440 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006441 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006442 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006443
6444 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006445 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006446
6447 // - if the subobject is an array, each element is assigned, in the
6448 // manner appropriate to the element type;
6449
6450 // Construct a loop over the array bounds, e.g.,
6451 //
6452 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6453 //
6454 // that will copy each of the array elements.
6455 QualType SizeType = S.Context.getSizeType();
6456
6457 // Create the iteration variable.
6458 IdentifierInfo *IterationVarName = 0;
6459 {
6460 llvm::SmallString<8> Str;
6461 llvm::raw_svector_ostream OS(Str);
6462 OS << "__i" << Depth;
6463 IterationVarName = &S.Context.Idents.get(OS.str());
6464 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006465 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006466 IterationVarName, SizeType,
6467 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00006468 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006469
6470 // Initialize the iteration variable to zero.
6471 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006472 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006473
6474 // Create a reference to the iteration variable; we'll use this several
6475 // times throughout.
6476 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00006477 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006478 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6479
6480 // Create the DeclStmt that holds the iteration variable.
6481 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6482
6483 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006484 llvm::APInt Upper
6485 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00006486 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00006487 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00006488 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6489 BO_NE, S.Context.BoolTy,
6490 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006491
6492 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006493 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00006494 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6495 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006496
6497 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006498 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6499 IterationVarRef, Loc));
6500 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6501 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006502
6503 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00006504 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6505 To, From, CopyingBaseSubobject,
6506 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00006507 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006508 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006509
6510 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00006511 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006512 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00006513 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00006514 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006515}
6516
Douglas Gregora376d102010-07-02 21:50:04 +00006517/// \brief Determine whether the given class has a copy assignment operator
6518/// that accepts a const-qualified argument.
6519static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6520 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6521
6522 if (!Class->hasDeclaredCopyAssignment())
6523 S.DeclareImplicitCopyAssignment(Class);
6524
6525 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6526 DeclarationName OpName
6527 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6528
6529 DeclContext::lookup_const_iterator Op, OpEnd;
6530 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6531 // C++ [class.copy]p9:
6532 // A user-declared copy assignment operator is a non-static non-template
6533 // member function of class X with exactly one parameter of type X, X&,
6534 // const X&, volatile X& or const volatile X&.
6535 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6536 if (!Method)
6537 continue;
6538
6539 if (Method->isStatic())
6540 continue;
6541 if (Method->getPrimaryTemplate())
6542 continue;
6543 const FunctionProtoType *FnType =
6544 Method->getType()->getAs<FunctionProtoType>();
6545 assert(FnType && "Overloaded operator has no prototype.");
6546 // Don't assert on this; an invalid decl might have been left in the AST.
6547 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6548 continue;
6549 bool AcceptsConst = true;
6550 QualType ArgType = FnType->getArgType(0);
6551 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6552 ArgType = Ref->getPointeeType();
6553 // Is it a non-const lvalue reference?
6554 if (!ArgType.isConstQualified())
6555 AcceptsConst = false;
6556 }
6557 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6558 continue;
6559
6560 // We have a single argument of type cv X or cv X&, i.e. we've found the
6561 // copy assignment operator. Return whether it accepts const arguments.
6562 return AcceptsConst;
6563 }
6564 assert(Class->isInvalidDecl() &&
6565 "No copy assignment operator declared in valid code.");
6566 return false;
6567}
6568
Sean Hunt30de05c2011-05-14 05:23:20 +00006569std::pair<Sema::ImplicitExceptionSpecification, bool>
6570Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6571 CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00006572 // C++ [class.copy]p10:
6573 // If the class definition does not explicitly declare a copy
6574 // assignment operator, one is declared implicitly.
6575 // The implicitly-defined copy assignment operator for a class X
6576 // will have the form
6577 //
6578 // X& X::operator=(const X&)
6579 //
6580 // if
6581 bool HasConstCopyAssignment = true;
6582
6583 // -- each direct base class B of X has a copy assignment operator
6584 // whose parameter is of type const B&, const volatile B& or B,
6585 // and
6586 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6587 BaseEnd = ClassDecl->bases_end();
6588 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6589 assert(!Base->getType()->isDependentType() &&
6590 "Cannot generate implicit members for class with dependent bases.");
6591 const CXXRecordDecl *BaseClassDecl
6592 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006593 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006594 }
6595
6596 // -- for all the nonstatic data members of X that are of a class
6597 // type M (or array thereof), each such class type has a copy
6598 // assignment operator whose parameter is of type const M&,
6599 // const volatile M& or M.
6600 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6601 FieldEnd = ClassDecl->field_end();
6602 HasConstCopyAssignment && Field != FieldEnd;
6603 ++Field) {
6604 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6605 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6606 const CXXRecordDecl *FieldClassDecl
6607 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006608 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006609 }
6610 }
6611
6612 // Otherwise, the implicitly declared copy assignment operator will
6613 // have the form
6614 //
6615 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00006616
Douglas Gregorb87786f2010-07-01 17:48:08 +00006617 // C++ [except.spec]p14:
6618 // An implicitly declared special member function (Clause 12) shall have an
6619 // exception-specification. [...]
6620 ImplicitExceptionSpecification ExceptSpec(Context);
6621 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6622 BaseEnd = ClassDecl->bases_end();
6623 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00006624 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006625 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006626
6627 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6628 DeclareImplicitCopyAssignment(BaseClassDecl);
6629
Douglas Gregorb87786f2010-07-01 17:48:08 +00006630 if (CXXMethodDecl *CopyAssign
6631 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6632 ExceptSpec.CalledDecl(CopyAssign);
6633 }
6634 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6635 FieldEnd = ClassDecl->field_end();
6636 Field != FieldEnd;
6637 ++Field) {
6638 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6639 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00006640 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006641 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006642
6643 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6644 DeclareImplicitCopyAssignment(FieldClassDecl);
6645
Douglas Gregorb87786f2010-07-01 17:48:08 +00006646 if (CXXMethodDecl *CopyAssign
6647 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6648 ExceptSpec.CalledDecl(CopyAssign);
6649 }
6650 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006651
Sean Hunt30de05c2011-05-14 05:23:20 +00006652 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6653}
6654
6655CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6656 // Note: The following rules are largely analoguous to the copy
6657 // constructor rules. Note that virtual bases are not taken into account
6658 // for determining the argument type of the operator. Note also that
6659 // operators taking an object instead of a reference are allowed.
6660
6661 ImplicitExceptionSpecification Spec(Context);
6662 bool Const;
6663 llvm::tie(Spec, Const) =
6664 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6665
6666 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6667 QualType RetType = Context.getLValueReferenceType(ArgType);
6668 if (Const)
6669 ArgType = ArgType.withConst();
6670 ArgType = Context.getLValueReferenceType(ArgType);
6671
Douglas Gregord3c35902010-07-01 16:36:15 +00006672 // An implicitly-declared copy assignment operator is an inline public
6673 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00006674 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00006675 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006676 SourceLocation ClassLoc = ClassDecl->getLocation();
6677 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00006678 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006679 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00006680 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00006681 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00006682 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00006683 /*isInline=*/true,
6684 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00006685 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00006686 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00006687 CopyAssignment->setImplicit();
6688 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00006689
6690 // Add the parameter to the operator.
6691 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006692 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00006693 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006694 SC_None,
6695 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00006696 CopyAssignment->setParams(&FromParam, 1);
6697
Douglas Gregora376d102010-07-02 21:50:04 +00006698 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00006699 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00006700
Douglas Gregor23c94db2010-07-02 17:43:08 +00006701 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00006702 PushOnScopeChains(CopyAssignment, S, false);
6703 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006704
Sean Hunt71a682f2011-05-18 03:41:58 +00006705 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6706 CopyAssignment->setDeletedAsWritten();
6707
Douglas Gregord3c35902010-07-01 16:36:15 +00006708 AddOverriddenMethods(ClassDecl, CopyAssignment);
6709 return CopyAssignment;
6710}
6711
Douglas Gregor06a9f362010-05-01 20:49:11 +00006712void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6713 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00006714 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006715 CopyAssignOperator->isOverloadedOperator() &&
6716 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006717 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006718 "DefineImplicitCopyAssignment called for wrong function");
6719
6720 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6721
6722 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6723 CopyAssignOperator->setInvalidDecl();
6724 return;
6725 }
6726
6727 CopyAssignOperator->setUsed();
6728
6729 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006730 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006731
6732 // C++0x [class.copy]p30:
6733 // The implicitly-defined or explicitly-defaulted copy assignment operator
6734 // for a non-union class X performs memberwise copy assignment of its
6735 // subobjects. The direct base classes of X are assigned first, in the
6736 // order of their declaration in the base-specifier-list, and then the
6737 // immediate non-static data members of X are assigned, in the order in
6738 // which they were declared in the class definition.
6739
6740 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00006741 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006742
6743 // The parameter for the "other" object, which we are copying from.
6744 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6745 Qualifiers OtherQuals = Other->getType().getQualifiers();
6746 QualType OtherRefType = Other->getType();
6747 if (const LValueReferenceType *OtherRef
6748 = OtherRefType->getAs<LValueReferenceType>()) {
6749 OtherRefType = OtherRef->getPointeeType();
6750 OtherQuals = OtherRefType.getQualifiers();
6751 }
6752
6753 // Our location for everything implicitly-generated.
6754 SourceLocation Loc = CopyAssignOperator->getLocation();
6755
6756 // Construct a reference to the "other" object. We'll be using this
6757 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00006758 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006759 assert(OtherRef && "Reference to parameter cannot fail!");
6760
6761 // Construct the "this" pointer. We'll be using this throughout the generated
6762 // ASTs.
6763 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6764 assert(This && "Reference to this cannot fail!");
6765
6766 // Assign base classes.
6767 bool Invalid = false;
6768 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6769 E = ClassDecl->bases_end(); Base != E; ++Base) {
6770 // Form the assignment:
6771 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6772 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00006773 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006774 Invalid = true;
6775 continue;
6776 }
6777
John McCallf871d0c2010-08-07 06:22:56 +00006778 CXXCastPath BasePath;
6779 BasePath.push_back(Base);
6780
Douglas Gregor06a9f362010-05-01 20:49:11 +00006781 // Construct the "from" expression, which is an implicit cast to the
6782 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00006783 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00006784 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6785 CK_UncheckedDerivedToBase,
6786 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006787
6788 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00006789 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006790
6791 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00006792 To = ImpCastExprToType(To.take(),
6793 Context.getCVRQualifiedType(BaseType,
6794 CopyAssignOperator->getTypeQualifiers()),
6795 CK_UncheckedDerivedToBase,
6796 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006797
6798 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00006799 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00006800 To.get(), From,
6801 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006802 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006803 Diag(CurrentLocation, diag::note_member_synthesized_at)
6804 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6805 CopyAssignOperator->setInvalidDecl();
6806 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006807 }
6808
6809 // Success! Record the copy.
6810 Statements.push_back(Copy.takeAs<Expr>());
6811 }
6812
6813 // \brief Reference to the __builtin_memcpy function.
6814 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006815 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006816 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006817
6818 // Assign non-static members.
6819 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6820 FieldEnd = ClassDecl->field_end();
6821 Field != FieldEnd; ++Field) {
6822 // Check for members of reference type; we can't copy those.
6823 if (Field->getType()->isReferenceType()) {
6824 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6825 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6826 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006827 Diag(CurrentLocation, diag::note_member_synthesized_at)
6828 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006829 Invalid = true;
6830 continue;
6831 }
6832
6833 // Check for members of const-qualified, non-class type.
6834 QualType BaseType = Context.getBaseElementType(Field->getType());
6835 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6836 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6837 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6838 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006839 Diag(CurrentLocation, diag::note_member_synthesized_at)
6840 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006841 Invalid = true;
6842 continue;
6843 }
6844
6845 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006846 if (FieldType->isIncompleteArrayType()) {
6847 assert(ClassDecl->hasFlexibleArrayMember() &&
6848 "Incomplete array type is not valid");
6849 continue;
6850 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006851
6852 // Build references to the field in the object we're copying from and to.
6853 CXXScopeSpec SS; // Intentionally empty
6854 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6855 LookupMemberName);
6856 MemberLookup.addDecl(*Field);
6857 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00006858 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00006859 Loc, /*IsArrow=*/false,
6860 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006861 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00006862 Loc, /*IsArrow=*/true,
6863 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006864 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6865 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6866
6867 // If the field should be copied with __builtin_memcpy rather than via
6868 // explicit assignments, do so. This optimization only applies for arrays
6869 // of scalars and arrays of class type with trivial copy-assignment
6870 // operators.
6871 if (FieldType->isArrayType() &&
6872 (!BaseType->isRecordType() ||
6873 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
6874 ->hasTrivialCopyAssignment())) {
6875 // Compute the size of the memory buffer to be copied.
6876 QualType SizeType = Context.getSizeType();
6877 llvm::APInt Size(Context.getTypeSize(SizeType),
6878 Context.getTypeSizeInChars(BaseType).getQuantity());
6879 for (const ConstantArrayType *Array
6880 = Context.getAsConstantArrayType(FieldType);
6881 Array;
6882 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00006883 llvm::APInt ArraySize
6884 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006885 Size *= ArraySize;
6886 }
6887
6888 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00006889 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6890 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006891
6892 bool NeedsCollectableMemCpy =
6893 (BaseType->isRecordType() &&
6894 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6895
6896 if (NeedsCollectableMemCpy) {
6897 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006898 // Create a reference to the __builtin_objc_memmove_collectable function.
6899 LookupResult R(*this,
6900 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006901 Loc, LookupOrdinaryName);
6902 LookupName(R, TUScope, true);
6903
6904 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6905 if (!CollectableMemCpy) {
6906 // Something went horribly wrong earlier, and we will have
6907 // complained about it.
6908 Invalid = true;
6909 continue;
6910 }
6911
6912 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6913 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00006914 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006915 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6916 }
6917 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006918 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006919 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006920 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6921 LookupOrdinaryName);
6922 LookupName(R, TUScope, true);
6923
6924 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6925 if (!BuiltinMemCpy) {
6926 // Something went horribly wrong earlier, and we will have complained
6927 // about it.
6928 Invalid = true;
6929 continue;
6930 }
6931
6932 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6933 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00006934 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006935 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6936 }
6937
John McCallca0408f2010-08-23 06:44:23 +00006938 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006939 CallArgs.push_back(To.takeAs<Expr>());
6940 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006941 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00006942 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006943 if (NeedsCollectableMemCpy)
6944 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00006945 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006946 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00006947 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006948 else
6949 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00006950 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006951 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00006952 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006953
Douglas Gregor06a9f362010-05-01 20:49:11 +00006954 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
6955 Statements.push_back(Call.takeAs<Expr>());
6956 continue;
6957 }
6958
6959 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00006960 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00006961 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006962 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006963 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006964 Diag(CurrentLocation, diag::note_member_synthesized_at)
6965 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6966 CopyAssignOperator->setInvalidDecl();
6967 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006968 }
6969
6970 // Success! Record the copy.
6971 Statements.push_back(Copy.takeAs<Stmt>());
6972 }
6973
6974 if (!Invalid) {
6975 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00006976 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006977
John McCall60d7b3a2010-08-24 06:29:42 +00006978 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006979 if (Return.isInvalid())
6980 Invalid = true;
6981 else {
6982 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006983
6984 if (Trap.hasErrorOccurred()) {
6985 Diag(CurrentLocation, diag::note_member_synthesized_at)
6986 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6987 Invalid = true;
6988 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006989 }
6990 }
6991
6992 if (Invalid) {
6993 CopyAssignOperator->setInvalidDecl();
6994 return;
6995 }
6996
John McCall60d7b3a2010-08-24 06:29:42 +00006997 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00006998 /*isStmtExpr=*/false);
6999 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7000 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007001
7002 if (ASTMutationListener *L = getASTMutationListener()) {
7003 L->CompletedImplicitDefinition(CopyAssignOperator);
7004 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007005}
7006
Sean Hunt49634cf2011-05-13 06:10:58 +00007007std::pair<Sema::ImplicitExceptionSpecification, bool>
7008Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007009 // C++ [class.copy]p5:
7010 // The implicitly-declared copy constructor for a class X will
7011 // have the form
7012 //
7013 // X::X(const X&)
7014 //
7015 // if
7016 bool HasConstCopyConstructor = true;
7017
7018 // -- each direct or virtual base class B of X has a copy
7019 // constructor whose first parameter is of type const B& or
7020 // const volatile B&, and
7021 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7022 BaseEnd = ClassDecl->bases_end();
7023 HasConstCopyConstructor && Base != BaseEnd;
7024 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007025 // Virtual bases are handled below.
7026 if (Base->isVirtual())
7027 continue;
7028
Douglas Gregor22584312010-07-02 23:41:54 +00007029 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00007030 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00007031 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7032 DeclareImplicitCopyConstructor(BaseClassDecl);
7033
Douglas Gregor598a8542010-07-01 18:27:03 +00007034 HasConstCopyConstructor
7035 = BaseClassDecl->hasConstCopyConstructor(Context);
7036 }
7037
7038 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7039 BaseEnd = ClassDecl->vbases_end();
7040 HasConstCopyConstructor && Base != BaseEnd;
7041 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007042 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007043 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00007044 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7045 DeclareImplicitCopyConstructor(BaseClassDecl);
7046
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007047 HasConstCopyConstructor
7048 = BaseClassDecl->hasConstCopyConstructor(Context);
7049 }
7050
7051 // -- for all the nonstatic data members of X that are of a
7052 // class type M (or array thereof), each such class type
7053 // has a copy constructor whose first parameter is of type
7054 // const M& or const volatile M&.
7055 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7056 FieldEnd = ClassDecl->field_end();
7057 HasConstCopyConstructor && Field != FieldEnd;
7058 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007059 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007060 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00007061 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00007062 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00007063 if (!FieldClassDecl->hasDeclaredCopyConstructor())
7064 DeclareImplicitCopyConstructor(FieldClassDecl);
7065
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007066 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00007067 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007068 }
7069 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007070 // Otherwise, the implicitly declared copy constructor will have
7071 // the form
7072 //
7073 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00007074
Douglas Gregor0d405db2010-07-01 20:59:04 +00007075 // C++ [except.spec]p14:
7076 // An implicitly declared special member function (Clause 12) shall have an
7077 // exception-specification. [...]
7078 ImplicitExceptionSpecification ExceptSpec(Context);
7079 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7080 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7081 BaseEnd = ClassDecl->bases_end();
7082 Base != BaseEnd;
7083 ++Base) {
7084 // Virtual bases are handled below.
7085 if (Base->isVirtual())
7086 continue;
7087
Douglas Gregor22584312010-07-02 23:41:54 +00007088 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007089 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00007090 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7091 DeclareImplicitCopyConstructor(BaseClassDecl);
7092
Douglas Gregor0d405db2010-07-01 20:59:04 +00007093 if (CXXConstructorDecl *CopyConstructor
7094 = BaseClassDecl->getCopyConstructor(Context, Quals))
7095 ExceptSpec.CalledDecl(CopyConstructor);
7096 }
7097 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7098 BaseEnd = ClassDecl->vbases_end();
7099 Base != BaseEnd;
7100 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007101 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007102 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00007103 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7104 DeclareImplicitCopyConstructor(BaseClassDecl);
7105
Douglas Gregor0d405db2010-07-01 20:59:04 +00007106 if (CXXConstructorDecl *CopyConstructor
7107 = BaseClassDecl->getCopyConstructor(Context, Quals))
7108 ExceptSpec.CalledDecl(CopyConstructor);
7109 }
7110 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7111 FieldEnd = ClassDecl->field_end();
7112 Field != FieldEnd;
7113 ++Field) {
7114 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7115 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00007116 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007117 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00007118 if (!FieldClassDecl->hasDeclaredCopyConstructor())
7119 DeclareImplicitCopyConstructor(FieldClassDecl);
7120
Douglas Gregor0d405db2010-07-01 20:59:04 +00007121 if (CXXConstructorDecl *CopyConstructor
7122 = FieldClassDecl->getCopyConstructor(Context, Quals))
7123 ExceptSpec.CalledDecl(CopyConstructor);
7124 }
7125 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007126
Sean Hunt49634cf2011-05-13 06:10:58 +00007127 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7128}
7129
7130CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7131 CXXRecordDecl *ClassDecl) {
7132 // C++ [class.copy]p4:
7133 // If the class definition does not explicitly declare a copy
7134 // constructor, one is declared implicitly.
7135
7136 ImplicitExceptionSpecification Spec(Context);
7137 bool Const;
7138 llvm::tie(Spec, Const) =
7139 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7140
7141 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7142 QualType ArgType = ClassType;
7143 if (Const)
7144 ArgType = ArgType.withConst();
7145 ArgType = Context.getLValueReferenceType(ArgType);
7146
7147 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7148
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007149 DeclarationName Name
7150 = Context.DeclarationNames.getCXXConstructorName(
7151 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007152 SourceLocation ClassLoc = ClassDecl->getLocation();
7153 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00007154
7155 // An implicitly-declared copy constructor is an inline public
7156 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007157 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007158 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007159 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00007160 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007161 /*TInfo=*/0,
7162 /*isExplicit=*/false,
7163 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00007164 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007165 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00007166 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007167 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7168
Douglas Gregor22584312010-07-02 23:41:54 +00007169 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00007170 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7171
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007172 // Add the parameter to the constructor.
7173 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007174 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007175 /*IdentifierInfo=*/0,
7176 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007177 SC_None,
7178 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007179 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00007180
Douglas Gregor23c94db2010-07-02 17:43:08 +00007181 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00007182 PushOnScopeChains(CopyConstructor, S, false);
7183 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00007184
7185 if (ShouldDeleteCopyConstructor(CopyConstructor))
7186 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007187
7188 return CopyConstructor;
7189}
7190
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007191void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00007192 CXXConstructorDecl *CopyConstructor) {
7193 assert((CopyConstructor->isDefaulted() &&
7194 CopyConstructor->isCopyConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00007195 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007196 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007197
Anders Carlsson63010a72010-04-23 16:24:12 +00007198 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007199 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007200
Douglas Gregor39957dc2010-05-01 15:04:51 +00007201 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007202 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007203
Sean Huntcbb67482011-01-08 20:30:50 +00007204 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007205 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00007206 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007207 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00007208 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007209 } else {
7210 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7211 CopyConstructor->getLocation(),
7212 MultiStmtArg(*this, 0, 0),
7213 /*isStmtExpr=*/false)
7214 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00007215 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007216
7217 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007218
7219 if (ASTMutationListener *L = getASTMutationListener()) {
7220 L->CompletedImplicitDefinition(CopyConstructor);
7221 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007222}
7223
John McCall60d7b3a2010-08-24 06:29:42 +00007224ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007225Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00007226 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00007227 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007228 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007229 unsigned ConstructKind,
7230 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007231 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00007232
Douglas Gregor2f599792010-04-02 18:24:57 +00007233 // C++0x [class.copy]p34:
7234 // When certain criteria are met, an implementation is allowed to
7235 // omit the copy/move construction of a class object, even if the
7236 // copy/move constructor and/or destructor for the object have
7237 // side effects. [...]
7238 // - when a temporary class object that has not been bound to a
7239 // reference (12.2) would be copied/moved to a class object
7240 // with the same cv-unqualified type, the copy/move operation
7241 // can be omitted by constructing the temporary object
7242 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00007243 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00007244 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00007245 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00007246 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007247 }
Mike Stump1eb44332009-09-09 15:08:12 +00007248
7249 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007250 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007251 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007252}
7253
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007254/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7255/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007256ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007257Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7258 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00007259 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007260 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007261 unsigned ConstructKind,
7262 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00007263 unsigned NumExprs = ExprArgs.size();
7264 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00007265
Nick Lewycky909a70d2011-03-25 01:44:32 +00007266 for (specific_attr_iterator<NonNullAttr>
7267 i = Constructor->specific_attr_begin<NonNullAttr>(),
7268 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7269 const NonNullAttr *NonNull = *i;
7270 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7271 }
7272
Douglas Gregor7edfb692009-11-23 12:27:39 +00007273 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00007274 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00007275 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00007276 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007277 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7278 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007279}
7280
Mike Stump1eb44332009-09-09 15:08:12 +00007281bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007282 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00007283 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00007284 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00007285 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00007286 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007287 move(Exprs), false, CXXConstructExpr::CK_Complete,
7288 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00007289 if (TempResult.isInvalid())
7290 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007291
Anders Carlssonda3f4e22009-08-25 05:12:04 +00007292 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00007293 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007294 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00007295 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00007296 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00007297
Anders Carlssonfe2de492009-08-25 05:18:00 +00007298 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00007299}
7300
John McCall68c6c9a2010-02-02 09:10:11 +00007301void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007302 if (VD->isInvalidDecl()) return;
7303
John McCall68c6c9a2010-02-02 09:10:11 +00007304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007305 if (ClassDecl->isInvalidDecl()) return;
7306 if (ClassDecl->hasTrivialDestructor()) return;
7307 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00007308
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007309 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7310 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7311 CheckDestructorAccess(VD->getLocation(), Destructor,
7312 PDiag(diag::err_access_dtor_var)
7313 << VD->getDeclName()
7314 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00007315
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007316 if (!VD->hasGlobalStorage()) return;
7317
7318 // Emit warning for non-trivial dtor in global scope (a real global,
7319 // class-static, function-static).
7320 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7321
7322 // TODO: this should be re-enabled for static locals by !CXAAtExit
7323 if (!VD->isStaticLocal())
7324 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007325}
7326
Mike Stump1eb44332009-09-09 15:08:12 +00007327/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007328/// ActOnDeclarator, when a C++ direct initializer is present.
7329/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00007330void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007331 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007332 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00007333 SourceLocation RParenLoc,
7334 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00007335 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007336
7337 // If there is no declaration, there was an error parsing it. Just ignore
7338 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00007339 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007340 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007341
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007342 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7343 if (!VDecl) {
7344 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7345 RealDecl->setInvalidDecl();
7346 return;
7347 }
7348
Richard Smith34b41d92011-02-20 03:19:35 +00007349 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7350 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00007351 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7352 if (Exprs.size() > 1) {
7353 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7354 diag::err_auto_var_init_multiple_expressions)
7355 << VDecl->getDeclName() << VDecl->getType()
7356 << VDecl->getSourceRange();
7357 RealDecl->setInvalidDecl();
7358 return;
7359 }
7360
7361 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00007362 TypeSourceInfo *DeducedType = 0;
7363 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00007364 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7365 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7366 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00007367 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00007368 RealDecl->setInvalidDecl();
7369 return;
7370 }
Richard Smitha085da82011-03-17 16:11:59 +00007371 VDecl->setTypeSourceInfo(DeducedType);
7372 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00007373
7374 // If this is a redeclaration, check that the type we just deduced matches
7375 // the previously declared type.
7376 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7377 MergeVarDeclTypes(VDecl, Old);
7378 }
7379
Douglas Gregor83ddad32009-08-26 21:14:46 +00007380 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007381 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007382 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7383 //
7384 // Clients that want to distinguish between the two forms, can check for
7385 // direct initializer using VarDecl::hasCXXDirectInitializer().
7386 // A major benefit is that clients that don't particularly care about which
7387 // exactly form was it (like the CodeGen) can handle both cases without
7388 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007389
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007390 // C++ 8.5p11:
7391 // The form of initialization (using parentheses or '=') is generally
7392 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007393 // class type.
7394
Douglas Gregor4dffad62010-02-11 22:55:30 +00007395 if (!VDecl->getType()->isDependentType() &&
7396 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00007397 diag::err_typecheck_decl_incomplete_type)) {
7398 VDecl->setInvalidDecl();
7399 return;
7400 }
7401
Douglas Gregor90f93822009-12-22 22:17:25 +00007402 // The variable can not have an abstract class type.
7403 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7404 diag::err_abstract_type_in_decl,
7405 AbstractVariableType))
7406 VDecl->setInvalidDecl();
7407
Sebastian Redl31310a22010-02-01 20:16:42 +00007408 const VarDecl *Def;
7409 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00007410 Diag(VDecl->getLocation(), diag::err_redefinition)
7411 << VDecl->getDeclName();
7412 Diag(Def->getLocation(), diag::note_previous_definition);
7413 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007414 return;
7415 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00007416
Douglas Gregor3a91abf2010-08-24 05:27:49 +00007417 // C++ [class.static.data]p4
7418 // If a static data member is of const integral or const
7419 // enumeration type, its declaration in the class definition can
7420 // specify a constant-initializer which shall be an integral
7421 // constant expression (5.19). In that case, the member can appear
7422 // in integral constant expressions. The member shall still be
7423 // defined in a namespace scope if it is used in the program and the
7424 // namespace scope definition shall not contain an initializer.
7425 //
7426 // We already performed a redefinition check above, but for static
7427 // data members we also need to check whether there was an in-class
7428 // declaration with an initializer.
7429 const VarDecl* PrevInit = 0;
7430 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7431 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7432 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7433 return;
7434 }
7435
Douglas Gregora31040f2010-12-16 01:31:22 +00007436 bool IsDependent = false;
7437 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7438 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7439 VDecl->setInvalidDecl();
7440 return;
7441 }
7442
7443 if (Exprs.get()[I]->isTypeDependent())
7444 IsDependent = true;
7445 }
7446
Douglas Gregor4dffad62010-02-11 22:55:30 +00007447 // If either the declaration has a dependent type or if any of the
7448 // expressions is type-dependent, we represent the initialization
7449 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00007450 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00007451 // Let clients know that initialization was done with a direct initializer.
7452 VDecl->setCXXDirectInitializer(true);
7453
7454 // Store the initialization expressions as a ParenListExpr.
7455 unsigned NumExprs = Exprs.size();
7456 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7457 (Expr **)Exprs.release(),
7458 NumExprs, RParenLoc));
7459 return;
7460 }
Douglas Gregor90f93822009-12-22 22:17:25 +00007461
7462 // Capture the variable that is being initialized and the style of
7463 // initialization.
7464 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7465
7466 // FIXME: Poor source location information.
7467 InitializationKind Kind
7468 = InitializationKind::CreateDirect(VDecl->getLocation(),
7469 LParenLoc, RParenLoc);
7470
7471 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00007472 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00007473 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00007474 if (Result.isInvalid()) {
7475 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007476 return;
7477 }
John McCallb4eb64d2010-10-08 02:01:28 +00007478
7479 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00007480
Douglas Gregor53c374f2010-12-07 00:41:46 +00007481 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00007482 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007483 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007484
John McCall2998d6b2011-01-19 11:48:09 +00007485 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007486}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00007487
Douglas Gregor39da0b82009-09-09 23:08:42 +00007488/// \brief Given a constructor and the set of arguments provided for the
7489/// constructor, convert the arguments and add any required default arguments
7490/// to form a proper call to this constructor.
7491///
7492/// \returns true if an error occurred, false otherwise.
7493bool
7494Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7495 MultiExprArg ArgsPtr,
7496 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00007497 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00007498 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7499 unsigned NumArgs = ArgsPtr.size();
7500 Expr **Args = (Expr **)ArgsPtr.get();
7501
7502 const FunctionProtoType *Proto
7503 = Constructor->getType()->getAs<FunctionProtoType>();
7504 assert(Proto && "Constructor without a prototype?");
7505 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00007506
7507 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007508 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00007509 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007510 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00007511 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007512
7513 VariadicCallType CallType =
7514 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7515 llvm::SmallVector<Expr *, 8> AllArgs;
7516 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7517 Proto, 0, Args, NumArgs, AllArgs,
7518 CallType);
7519 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7520 ConvertedArgs.push_back(AllArgs[i]);
7521 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00007522}
7523
Anders Carlsson20d45d22009-12-12 00:32:00 +00007524static inline bool
7525CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7526 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007527 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00007528 if (isa<NamespaceDecl>(DC)) {
7529 return SemaRef.Diag(FnDecl->getLocation(),
7530 diag::err_operator_new_delete_declared_in_namespace)
7531 << FnDecl->getDeclName();
7532 }
7533
7534 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00007535 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007536 return SemaRef.Diag(FnDecl->getLocation(),
7537 diag::err_operator_new_delete_declared_static)
7538 << FnDecl->getDeclName();
7539 }
7540
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00007541 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00007542}
7543
Anders Carlsson156c78e2009-12-13 17:53:43 +00007544static inline bool
7545CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7546 CanQualType ExpectedResultType,
7547 CanQualType ExpectedFirstParamType,
7548 unsigned DependentParamTypeDiag,
7549 unsigned InvalidParamTypeDiag) {
7550 QualType ResultType =
7551 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7552
7553 // Check that the result type is not dependent.
7554 if (ResultType->isDependentType())
7555 return SemaRef.Diag(FnDecl->getLocation(),
7556 diag::err_operator_new_delete_dependent_result_type)
7557 << FnDecl->getDeclName() << ExpectedResultType;
7558
7559 // Check that the result type is what we expect.
7560 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7561 return SemaRef.Diag(FnDecl->getLocation(),
7562 diag::err_operator_new_delete_invalid_result_type)
7563 << FnDecl->getDeclName() << ExpectedResultType;
7564
7565 // A function template must have at least 2 parameters.
7566 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7567 return SemaRef.Diag(FnDecl->getLocation(),
7568 diag::err_operator_new_delete_template_too_few_parameters)
7569 << FnDecl->getDeclName();
7570
7571 // The function decl must have at least 1 parameter.
7572 if (FnDecl->getNumParams() == 0)
7573 return SemaRef.Diag(FnDecl->getLocation(),
7574 diag::err_operator_new_delete_too_few_parameters)
7575 << FnDecl->getDeclName();
7576
7577 // Check the the first parameter type is not dependent.
7578 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7579 if (FirstParamType->isDependentType())
7580 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7581 << FnDecl->getDeclName() << ExpectedFirstParamType;
7582
7583 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00007584 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00007585 ExpectedFirstParamType)
7586 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7587 << FnDecl->getDeclName() << ExpectedFirstParamType;
7588
7589 return false;
7590}
7591
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007592static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00007593CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007594 // C++ [basic.stc.dynamic.allocation]p1:
7595 // A program is ill-formed if an allocation function is declared in a
7596 // namespace scope other than global scope or declared static in global
7597 // scope.
7598 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7599 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00007600
7601 CanQualType SizeTy =
7602 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7603
7604 // C++ [basic.stc.dynamic.allocation]p1:
7605 // The return type shall be void*. The first parameter shall have type
7606 // std::size_t.
7607 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7608 SizeTy,
7609 diag::err_operator_new_dependent_param_type,
7610 diag::err_operator_new_param_type))
7611 return true;
7612
7613 // C++ [basic.stc.dynamic.allocation]p1:
7614 // The first parameter shall not have an associated default argument.
7615 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00007616 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00007617 diag::err_operator_new_default_arg)
7618 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7619
7620 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00007621}
7622
7623static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007624CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7625 // C++ [basic.stc.dynamic.deallocation]p1:
7626 // A program is ill-formed if deallocation functions are declared in a
7627 // namespace scope other than global scope or declared static in global
7628 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00007629 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7630 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007631
7632 // C++ [basic.stc.dynamic.deallocation]p2:
7633 // Each deallocation function shall return void and its first parameter
7634 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00007635 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7636 SemaRef.Context.VoidPtrTy,
7637 diag::err_operator_delete_dependent_param_type,
7638 diag::err_operator_delete_param_type))
7639 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007640
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007641 return false;
7642}
7643
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007644/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7645/// of this overloaded operator is well-formed. If so, returns false;
7646/// otherwise, emits appropriate diagnostics and returns true.
7647bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007648 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007649 "Expected an overloaded operator declaration");
7650
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007651 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7652
Mike Stump1eb44332009-09-09 15:08:12 +00007653 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007654 // The allocation and deallocation functions, operator new,
7655 // operator new[], operator delete and operator delete[], are
7656 // described completely in 3.7.3. The attributes and restrictions
7657 // found in the rest of this subclause do not apply to them unless
7658 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00007659 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007660 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00007661
Anders Carlssona3ccda52009-12-12 00:26:23 +00007662 if (Op == OO_New || Op == OO_Array_New)
7663 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007664
7665 // C++ [over.oper]p6:
7666 // An operator function shall either be a non-static member
7667 // function or be a non-member function and have at least one
7668 // parameter whose type is a class, a reference to a class, an
7669 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007670 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7671 if (MethodDecl->isStatic())
7672 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007673 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007674 } else {
7675 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007676 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7677 ParamEnd = FnDecl->param_end();
7678 Param != ParamEnd; ++Param) {
7679 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00007680 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7681 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007682 ClassOrEnumParam = true;
7683 break;
7684 }
7685 }
7686
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007687 if (!ClassOrEnumParam)
7688 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007689 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007690 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007691 }
7692
7693 // C++ [over.oper]p8:
7694 // An operator function cannot have default arguments (8.3.6),
7695 // except where explicitly stated below.
7696 //
Mike Stump1eb44332009-09-09 15:08:12 +00007697 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007698 // (C++ [over.call]p1).
7699 if (Op != OO_Call) {
7700 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7701 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00007702 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00007703 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00007704 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00007705 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007706 }
7707 }
7708
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007709 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7710 { false, false, false }
7711#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7712 , { Unary, Binary, MemberOnly }
7713#include "clang/Basic/OperatorKinds.def"
7714 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007715
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007716 bool CanBeUnaryOperator = OperatorUses[Op][0];
7717 bool CanBeBinaryOperator = OperatorUses[Op][1];
7718 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007719
7720 // C++ [over.oper]p8:
7721 // [...] Operator functions cannot have more or fewer parameters
7722 // than the number required for the corresponding operator, as
7723 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00007724 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007725 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007726 if (Op != OO_Call &&
7727 ((NumParams == 1 && !CanBeUnaryOperator) ||
7728 (NumParams == 2 && !CanBeBinaryOperator) ||
7729 (NumParams < 1) || (NumParams > 2))) {
7730 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00007731 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007732 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007733 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007734 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007735 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007736 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007737 assert(CanBeBinaryOperator &&
7738 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00007739 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007740 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007741
Chris Lattner416e46f2008-11-21 07:57:12 +00007742 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007743 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007744 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00007745
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007746 // Overloaded operators other than operator() cannot be variadic.
7747 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00007748 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007749 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007750 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007751 }
7752
7753 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007754 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7755 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007756 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007757 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007758 }
7759
7760 // C++ [over.inc]p1:
7761 // The user-defined function called operator++ implements the
7762 // prefix and postfix ++ operator. If this function is a member
7763 // function with no parameters, or a non-member function with one
7764 // parameter of class or enumeration type, it defines the prefix
7765 // increment operator ++ for objects of that type. If the function
7766 // is a member function with one parameter (which shall be of type
7767 // int) or a non-member function with two parameters (the second
7768 // of which shall be of type int), it defines the postfix
7769 // increment operator ++ for objects of that type.
7770 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7771 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7772 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00007773 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007774 ParamIsInt = BT->getKind() == BuiltinType::Int;
7775
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007776 if (!ParamIsInt)
7777 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00007778 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00007779 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007780 }
7781
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007782 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007783}
Chris Lattner5a003a42008-12-17 07:09:26 +00007784
Sean Hunta6c058d2010-01-13 09:01:02 +00007785/// CheckLiteralOperatorDeclaration - Check whether the declaration
7786/// of this literal operator function is well-formed. If so, returns
7787/// false; otherwise, emits appropriate diagnostics and returns true.
7788bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7789 DeclContext *DC = FnDecl->getDeclContext();
7790 Decl::Kind Kind = DC->getDeclKind();
7791 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7792 Kind != Decl::LinkageSpec) {
7793 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7794 << FnDecl->getDeclName();
7795 return true;
7796 }
7797
7798 bool Valid = false;
7799
Sean Hunt216c2782010-04-07 23:11:06 +00007800 // template <char...> type operator "" name() is the only valid template
7801 // signature, and the only valid signature with no parameters.
7802 if (FnDecl->param_size() == 0) {
7803 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7804 // Must have only one template parameter
7805 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7806 if (Params->size() == 1) {
7807 NonTypeTemplateParmDecl *PmDecl =
7808 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00007809
Sean Hunt216c2782010-04-07 23:11:06 +00007810 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00007811 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7812 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7813 Valid = true;
7814 }
7815 }
7816 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00007817 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00007818 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7819
Sean Hunta6c058d2010-01-13 09:01:02 +00007820 QualType T = (*Param)->getType();
7821
Sean Hunt30019c02010-04-07 22:57:35 +00007822 // unsigned long long int, long double, and any character type are allowed
7823 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00007824 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7825 Context.hasSameType(T, Context.LongDoubleTy) ||
7826 Context.hasSameType(T, Context.CharTy) ||
7827 Context.hasSameType(T, Context.WCharTy) ||
7828 Context.hasSameType(T, Context.Char16Ty) ||
7829 Context.hasSameType(T, Context.Char32Ty)) {
7830 if (++Param == FnDecl->param_end())
7831 Valid = true;
7832 goto FinishedParams;
7833 }
7834
Sean Hunt30019c02010-04-07 22:57:35 +00007835 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00007836 const PointerType *PT = T->getAs<PointerType>();
7837 if (!PT)
7838 goto FinishedParams;
7839 T = PT->getPointeeType();
7840 if (!T.isConstQualified())
7841 goto FinishedParams;
7842 T = T.getUnqualifiedType();
7843
7844 // Move on to the second parameter;
7845 ++Param;
7846
7847 // If there is no second parameter, the first must be a const char *
7848 if (Param == FnDecl->param_end()) {
7849 if (Context.hasSameType(T, Context.CharTy))
7850 Valid = true;
7851 goto FinishedParams;
7852 }
7853
7854 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7855 // are allowed as the first parameter to a two-parameter function
7856 if (!(Context.hasSameType(T, Context.CharTy) ||
7857 Context.hasSameType(T, Context.WCharTy) ||
7858 Context.hasSameType(T, Context.Char16Ty) ||
7859 Context.hasSameType(T, Context.Char32Ty)))
7860 goto FinishedParams;
7861
7862 // The second and final parameter must be an std::size_t
7863 T = (*Param)->getType().getUnqualifiedType();
7864 if (Context.hasSameType(T, Context.getSizeType()) &&
7865 ++Param == FnDecl->param_end())
7866 Valid = true;
7867 }
7868
7869 // FIXME: This diagnostic is absolutely terrible.
7870FinishedParams:
7871 if (!Valid) {
7872 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7873 << FnDecl->getDeclName();
7874 return true;
7875 }
7876
7877 return false;
7878}
7879
Douglas Gregor074149e2009-01-05 19:45:36 +00007880/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7881/// linkage specification, including the language and (if present)
7882/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7883/// the location of the language string literal, which is provided
7884/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7885/// the '{' brace. Otherwise, this linkage specification does not
7886/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00007887Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7888 SourceLocation LangLoc,
7889 llvm::StringRef Lang,
7890 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00007891 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007892 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007893 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007894 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007895 Language = LinkageSpecDecl::lang_cxx;
7896 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00007897 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00007898 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00007899 }
Mike Stump1eb44332009-09-09 15:08:12 +00007900
Chris Lattnercc98eac2008-12-17 07:13:27 +00007901 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00007902
Douglas Gregor074149e2009-01-05 19:45:36 +00007903 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007904 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007905 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00007906 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00007907 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00007908}
7909
Abramo Bagnara35f9a192010-07-30 16:47:02 +00007910/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00007911/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7912/// valid, it's the position of the closing '}' brace in a linkage
7913/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00007914Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00007915 Decl *LinkageSpec,
7916 SourceLocation RBraceLoc) {
7917 if (LinkageSpec) {
7918 if (RBraceLoc.isValid()) {
7919 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7920 LSDecl->setRBraceLoc(RBraceLoc);
7921 }
Douglas Gregor074149e2009-01-05 19:45:36 +00007922 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00007923 }
Douglas Gregor074149e2009-01-05 19:45:36 +00007924 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00007925}
7926
Douglas Gregord308e622009-05-18 20:51:54 +00007927/// \brief Perform semantic analysis for the variable declaration that
7928/// occurs within a C++ catch clause, returning the newly-created
7929/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007930VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00007931 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007932 SourceLocation StartLoc,
7933 SourceLocation Loc,
7934 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00007935 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00007936 QualType ExDeclType = TInfo->getType();
7937
Sebastian Redl4b07b292008-12-22 19:15:10 +00007938 // Arrays and functions decay.
7939 if (ExDeclType->isArrayType())
7940 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7941 else if (ExDeclType->isFunctionType())
7942 ExDeclType = Context.getPointerType(ExDeclType);
7943
7944 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7945 // The exception-declaration shall not denote a pointer or reference to an
7946 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007947 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00007948 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00007949 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007950 Invalid = true;
7951 }
Douglas Gregord308e622009-05-18 20:51:54 +00007952
Douglas Gregora2762912010-03-08 01:47:36 +00007953 // GCC allows catching pointers and references to incomplete types
7954 // as an extension; so do we, but we warn by default.
7955
Sebastian Redl4b07b292008-12-22 19:15:10 +00007956 QualType BaseType = ExDeclType;
7957 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007958 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00007959 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00007960 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007961 BaseType = Ptr->getPointeeType();
7962 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00007963 DK = diag::ext_catch_incomplete_ptr;
7964 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00007965 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007966 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00007967 BaseType = Ref->getPointeeType();
7968 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00007969 DK = diag::ext_catch_incomplete_ref;
7970 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007971 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007972 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00007973 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
7974 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00007975 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007976
Mike Stump1eb44332009-09-09 15:08:12 +00007977 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00007978 RequireNonAbstractType(Loc, ExDeclType,
7979 diag::err_abstract_type_in_decl,
7980 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00007981 Invalid = true;
7982
John McCall5a180392010-07-24 00:37:23 +00007983 // Only the non-fragile NeXT runtime currently supports C++ catches
7984 // of ObjC types, and no runtime supports catching ObjC types by value.
7985 if (!Invalid && getLangOptions().ObjC1) {
7986 QualType T = ExDeclType;
7987 if (const ReferenceType *RT = T->getAs<ReferenceType>())
7988 T = RT->getPointeeType();
7989
7990 if (T->isObjCObjectType()) {
7991 Diag(Loc, diag::err_objc_object_catch);
7992 Invalid = true;
7993 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00007994 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00007995 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
7996 Invalid = true;
7997 }
7998 }
7999 }
8000
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008001 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8002 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00008003 ExDecl->setExceptionVariable(true);
8004
Douglas Gregor6d182892010-03-05 23:38:39 +00008005 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00008006 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00008007 // C++ [except.handle]p16:
8008 // The object declared in an exception-declaration or, if the
8009 // exception-declaration does not specify a name, a temporary (12.2) is
8010 // copy-initialized (8.5) from the exception object. [...]
8011 // The object is destroyed when the handler exits, after the destruction
8012 // of any automatic objects initialized within the handler.
8013 //
8014 // We just pretend to initialize the object with itself, then make sure
8015 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00008016 QualType initType = ExDeclType;
8017
8018 InitializedEntity entity =
8019 InitializedEntity::InitializeVariable(ExDecl);
8020 InitializationKind initKind =
8021 InitializationKind::CreateCopy(Loc, SourceLocation());
8022
8023 Expr *opaqueValue =
8024 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8025 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8026 ExprResult result = sequence.Perform(*this, entity, initKind,
8027 MultiExprArg(&opaqueValue, 1));
8028 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00008029 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00008030 else {
8031 // If the constructor used was non-trivial, set this as the
8032 // "initializer".
8033 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8034 if (!construct->getConstructor()->isTrivial()) {
8035 Expr *init = MaybeCreateExprWithCleanups(construct);
8036 ExDecl->setInit(init);
8037 }
8038
8039 // And make sure it's destructable.
8040 FinalizeVarWithDestructor(ExDecl, recordType);
8041 }
Douglas Gregor6d182892010-03-05 23:38:39 +00008042 }
8043 }
8044
Douglas Gregord308e622009-05-18 20:51:54 +00008045 if (Invalid)
8046 ExDecl->setInvalidDecl();
8047
8048 return ExDecl;
8049}
8050
8051/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8052/// handler.
John McCalld226f652010-08-21 09:40:31 +00008053Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00008054 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00008055 bool Invalid = D.isInvalidType();
8056
8057 // Check for unexpanded parameter packs.
8058 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8059 UPPC_ExceptionType)) {
8060 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8061 D.getIdentifierLoc());
8062 Invalid = true;
8063 }
8064
Sebastian Redl4b07b292008-12-22 19:15:10 +00008065 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00008066 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00008067 LookupOrdinaryName,
8068 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008069 // The scope should be freshly made just for us. There is just no way
8070 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00008071 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00008072 if (PrevDecl->isTemplateParameter()) {
8073 // Maybe we will complain about the shadowed template parameter.
8074 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008075 }
8076 }
8077
Chris Lattnereaaebc72009-04-25 08:06:05 +00008078 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008079 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8080 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00008081 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008082 }
8083
Douglas Gregor83cb9422010-09-09 17:09:21 +00008084 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008085 D.getSourceRange().getBegin(),
8086 D.getIdentifierLoc(),
8087 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00008088 if (Invalid)
8089 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00008090
Sebastian Redl4b07b292008-12-22 19:15:10 +00008091 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008092 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00008093 PushOnScopeChains(ExDecl, S);
8094 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008095 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008096
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008097 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00008098 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008099}
Anders Carlssonfb311762009-03-14 00:25:26 +00008100
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008101Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008102 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008103 Expr *AssertMessageExpr_,
8104 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00008105 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00008106
Anders Carlssonc3082412009-03-14 00:33:21 +00008107 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8108 llvm::APSInt Value(32);
8109 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008110 Diag(StaticAssertLoc,
8111 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00008112 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008113 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00008114 }
Anders Carlssonfb311762009-03-14 00:25:26 +00008115
Anders Carlssonc3082412009-03-14 00:33:21 +00008116 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008117 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00008118 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00008119 }
8120 }
Mike Stump1eb44332009-09-09 15:08:12 +00008121
Douglas Gregor399ad972010-12-15 23:55:21 +00008122 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8123 return 0;
8124
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008125 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8126 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00008127
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008128 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00008129 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00008130}
Sebastian Redl50de12f2009-03-24 22:27:57 +00008131
Douglas Gregor1d869352010-04-07 16:53:43 +00008132/// \brief Perform semantic analysis of the given friend type declaration.
8133///
8134/// \returns A friend declaration that.
8135FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8136 TypeSourceInfo *TSInfo) {
8137 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8138
8139 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008140 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00008141
Douglas Gregor06245bf2010-04-07 17:57:12 +00008142 if (!getLangOptions().CPlusPlus0x) {
8143 // C++03 [class.friend]p2:
8144 // An elaborated-type-specifier shall be used in a friend declaration
8145 // for a class.*
8146 //
8147 // * The class-key of the elaborated-type-specifier is required.
8148 if (!ActiveTemplateInstantiations.empty()) {
8149 // Do not complain about the form of friend template types during
8150 // template instantiation; we will already have complained when the
8151 // template was declared.
8152 } else if (!T->isElaboratedTypeSpecifier()) {
8153 // If we evaluated the type to a record type, suggest putting
8154 // a tag in front.
8155 if (const RecordType *RT = T->getAs<RecordType>()) {
8156 RecordDecl *RD = RT->getDecl();
8157
8158 std::string InsertionText = std::string(" ") + RD->getKindName();
8159
8160 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8161 << (unsigned) RD->getTagKind()
8162 << T
8163 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8164 InsertionText);
8165 } else {
8166 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8167 << T
8168 << SourceRange(FriendLoc, TypeRange.getEnd());
8169 }
8170 } else if (T->getAs<EnumType>()) {
8171 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00008172 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00008173 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00008174 }
8175 }
8176
Douglas Gregor06245bf2010-04-07 17:57:12 +00008177 // C++0x [class.friend]p3:
8178 // If the type specifier in a friend declaration designates a (possibly
8179 // cv-qualified) class type, that class is declared as a friend; otherwise,
8180 // the friend declaration is ignored.
8181
8182 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8183 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00008184
8185 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8186}
8187
John McCall9a34edb2010-10-19 01:40:49 +00008188/// Handle a friend tag declaration where the scope specifier was
8189/// templated.
8190Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8191 unsigned TagSpec, SourceLocation TagLoc,
8192 CXXScopeSpec &SS,
8193 IdentifierInfo *Name, SourceLocation NameLoc,
8194 AttributeList *Attr,
8195 MultiTemplateParamsArg TempParamLists) {
8196 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8197
8198 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00008199 bool Invalid = false;
8200
8201 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00008202 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00008203 TempParamLists.get(),
8204 TempParamLists.size(),
8205 /*friend*/ true,
8206 isExplicitSpecialization,
8207 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00008208 if (TemplateParams->size() > 0) {
8209 // This is a declaration of a class template.
8210 if (Invalid)
8211 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008212
John McCall9a34edb2010-10-19 01:40:49 +00008213 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8214 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008215 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008216 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008217 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00008218 } else {
8219 // The "template<>" header is extraneous.
8220 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8221 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8222 isExplicitSpecialization = true;
8223 }
8224 }
8225
8226 if (Invalid) return 0;
8227
8228 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8229
8230 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008231 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00008232 if (TempParamLists.get()[I]->size()) {
8233 isAllExplicitSpecializations = false;
8234 break;
8235 }
8236 }
8237
8238 // FIXME: don't ignore attributes.
8239
8240 // If it's explicit specializations all the way down, just forget
8241 // about the template header and build an appropriate non-templated
8242 // friend. TODO: for source fidelity, remember the headers.
8243 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00008244 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00008245 ElaboratedTypeKeyword Keyword
8246 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008247 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00008248 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008249 if (T.isNull())
8250 return 0;
8251
8252 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8253 if (isa<DependentNameType>(T)) {
8254 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8255 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008256 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008257 TL.setNameLoc(NameLoc);
8258 } else {
8259 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8260 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00008261 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008262 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8263 }
8264
8265 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8266 TSI, FriendLoc);
8267 Friend->setAccess(AS_public);
8268 CurContext->addDecl(Friend);
8269 return Friend;
8270 }
8271
8272 // Handle the case of a templated-scope friend class. e.g.
8273 // template <class T> class A<T>::B;
8274 // FIXME: we don't support these right now.
8275 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8276 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8277 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8278 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8279 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008280 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00008281 TL.setNameLoc(NameLoc);
8282
8283 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8284 TSI, FriendLoc);
8285 Friend->setAccess(AS_public);
8286 Friend->setUnsupportedFriend(true);
8287 CurContext->addDecl(Friend);
8288 return Friend;
8289}
8290
8291
John McCalldd4a3b02009-09-16 22:47:08 +00008292/// Handle a friend type declaration. This works in tandem with
8293/// ActOnTag.
8294///
8295/// Notes on friend class templates:
8296///
8297/// We generally treat friend class declarations as if they were
8298/// declaring a class. So, for example, the elaborated type specifier
8299/// in a friend declaration is required to obey the restrictions of a
8300/// class-head (i.e. no typedefs in the scope chain), template
8301/// parameters are required to match up with simple template-ids, &c.
8302/// However, unlike when declaring a template specialization, it's
8303/// okay to refer to a template specialization without an empty
8304/// template parameter declaration, e.g.
8305/// friend class A<T>::B<unsigned>;
8306/// We permit this as a special case; if there are any template
8307/// parameters present at all, require proper matching, i.e.
8308/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00008309Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00008310 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00008311 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00008312
8313 assert(DS.isFriendSpecified());
8314 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8315
John McCalldd4a3b02009-09-16 22:47:08 +00008316 // Try to convert the decl specifier to a type. This works for
8317 // friend templates because ActOnTag never produces a ClassTemplateDecl
8318 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00008319 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00008320 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8321 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00008322 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00008323 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008324
Douglas Gregor6ccab972010-12-16 01:14:37 +00008325 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8326 return 0;
8327
John McCalldd4a3b02009-09-16 22:47:08 +00008328 // This is definitely an error in C++98. It's probably meant to
8329 // be forbidden in C++0x, too, but the specification is just
8330 // poorly written.
8331 //
8332 // The problem is with declarations like the following:
8333 // template <T> friend A<T>::foo;
8334 // where deciding whether a class C is a friend or not now hinges
8335 // on whether there exists an instantiation of A that causes
8336 // 'foo' to equal C. There are restrictions on class-heads
8337 // (which we declare (by fiat) elaborated friend declarations to
8338 // be) that makes this tractable.
8339 //
8340 // FIXME: handle "template <> friend class A<T>;", which
8341 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00008342 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00008343 Diag(Loc, diag::err_tagless_friend_type_template)
8344 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008345 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00008346 }
Douglas Gregor1d869352010-04-07 16:53:43 +00008347
John McCall02cace72009-08-28 07:59:38 +00008348 // C++98 [class.friend]p1: A friend of a class is a function
8349 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00008350 // This is fixed in DR77, which just barely didn't make the C++03
8351 // deadline. It's also a very silly restriction that seriously
8352 // affects inner classes and which nobody else seems to implement;
8353 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00008354 //
8355 // But note that we could warn about it: it's always useless to
8356 // friend one of your own members (it's not, however, worthless to
8357 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00008358
John McCalldd4a3b02009-09-16 22:47:08 +00008359 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00008360 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00008361 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00008362 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00008363 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00008364 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00008365 DS.getFriendSpecLoc());
8366 else
Douglas Gregor1d869352010-04-07 16:53:43 +00008367 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8368
8369 if (!D)
John McCalld226f652010-08-21 09:40:31 +00008370 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00008371
John McCalldd4a3b02009-09-16 22:47:08 +00008372 D->setAccess(AS_public);
8373 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00008374
John McCalld226f652010-08-21 09:40:31 +00008375 return D;
John McCall02cace72009-08-28 07:59:38 +00008376}
8377
John McCall337ec3d2010-10-12 23:13:28 +00008378Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8379 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00008380 const DeclSpec &DS = D.getDeclSpec();
8381
8382 assert(DS.isFriendSpecified());
8383 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8384
8385 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00008386 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8387 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00008388
8389 // C++ [class.friend]p1
8390 // A friend of a class is a function or class....
8391 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00008392 // It *doesn't* see through dependent types, which is correct
8393 // according to [temp.arg.type]p3:
8394 // If a declaration acquires a function type through a
8395 // type dependent on a template-parameter and this causes
8396 // a declaration that does not use the syntactic form of a
8397 // function declarator to have a function type, the program
8398 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00008399 if (!T->isFunctionType()) {
8400 Diag(Loc, diag::err_unexpected_friend);
8401
8402 // It might be worthwhile to try to recover by creating an
8403 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00008404 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008405 }
8406
8407 // C++ [namespace.memdef]p3
8408 // - If a friend declaration in a non-local class first declares a
8409 // class or function, the friend class or function is a member
8410 // of the innermost enclosing namespace.
8411 // - The name of the friend is not found by simple name lookup
8412 // until a matching declaration is provided in that namespace
8413 // scope (either before or after the class declaration granting
8414 // friendship).
8415 // - If a friend function is called, its name may be found by the
8416 // name lookup that considers functions from namespaces and
8417 // classes associated with the types of the function arguments.
8418 // - When looking for a prior declaration of a class or a function
8419 // declared as a friend, scopes outside the innermost enclosing
8420 // namespace scope are not considered.
8421
John McCall337ec3d2010-10-12 23:13:28 +00008422 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00008423 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8424 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00008425 assert(Name);
8426
Douglas Gregor6ccab972010-12-16 01:14:37 +00008427 // Check for unexpanded parameter packs.
8428 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8429 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8430 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8431 return 0;
8432
John McCall67d1a672009-08-06 02:15:43 +00008433 // The context we found the declaration in, or in which we should
8434 // create the declaration.
8435 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00008436 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00008437 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00008438 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00008439
John McCall337ec3d2010-10-12 23:13:28 +00008440 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00008441
John McCall337ec3d2010-10-12 23:13:28 +00008442 // There are four cases here.
8443 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00008444 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00008445 // there as appropriate.
8446 // Recover from invalid scope qualifiers as if they just weren't there.
8447 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00008448 // C++0x [namespace.memdef]p3:
8449 // If the name in a friend declaration is neither qualified nor
8450 // a template-id and the declaration is a function or an
8451 // elaborated-type-specifier, the lookup to determine whether
8452 // the entity has been previously declared shall not consider
8453 // any scopes outside the innermost enclosing namespace.
8454 // C++0x [class.friend]p11:
8455 // If a friend declaration appears in a local class and the name
8456 // specified is an unqualified name, a prior declaration is
8457 // looked up without considering scopes that are outside the
8458 // innermost enclosing non-class scope. For a friend function
8459 // declaration, if there is no prior declaration, the program is
8460 // ill-formed.
8461 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00008462 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00008463
John McCall29ae6e52010-10-13 05:45:15 +00008464 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00008465 DC = CurContext;
8466 while (true) {
8467 // Skip class contexts. If someone can cite chapter and verse
8468 // for this behavior, that would be nice --- it's what GCC and
8469 // EDG do, and it seems like a reasonable intent, but the spec
8470 // really only says that checks for unqualified existing
8471 // declarations should stop at the nearest enclosing namespace,
8472 // not that they should only consider the nearest enclosing
8473 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00008474 while (DC->isRecord())
8475 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00008476
John McCall68263142009-11-18 22:49:29 +00008477 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00008478
8479 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00008480 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00008481 break;
John McCall29ae6e52010-10-13 05:45:15 +00008482
John McCall8a407372010-10-14 22:22:28 +00008483 if (isTemplateId) {
8484 if (isa<TranslationUnitDecl>(DC)) break;
8485 } else {
8486 if (DC->isFileContext()) break;
8487 }
John McCall67d1a672009-08-06 02:15:43 +00008488 DC = DC->getParent();
8489 }
8490
8491 // C++ [class.friend]p1: A friend of a class is a function or
8492 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00008493 // C++0x changes this for both friend types and functions.
8494 // Most C++ 98 compilers do seem to give an error here, so
8495 // we do, too.
John McCall68263142009-11-18 22:49:29 +00008496 if (!Previous.empty() && DC->Equals(CurContext)
8497 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00008498 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00008499
John McCall380aaa42010-10-13 06:22:15 +00008500 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00008501
John McCall337ec3d2010-10-12 23:13:28 +00008502 // - There's a non-dependent scope specifier, in which case we
8503 // compute it and do a previous lookup there for a function
8504 // or function template.
8505 } else if (!SS.getScopeRep()->isDependent()) {
8506 DC = computeDeclContext(SS);
8507 if (!DC) return 0;
8508
8509 if (RequireCompleteDeclContext(SS, DC)) return 0;
8510
8511 LookupQualifiedName(Previous, DC);
8512
8513 // Ignore things found implicitly in the wrong scope.
8514 // TODO: better diagnostics for this case. Suggesting the right
8515 // qualified scope would be nice...
8516 LookupResult::Filter F = Previous.makeFilter();
8517 while (F.hasNext()) {
8518 NamedDecl *D = F.next();
8519 if (!DC->InEnclosingNamespaceSetOf(
8520 D->getDeclContext()->getRedeclContext()))
8521 F.erase();
8522 }
8523 F.done();
8524
8525 if (Previous.empty()) {
8526 D.setInvalidType();
8527 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8528 return 0;
8529 }
8530
8531 // C++ [class.friend]p1: A friend of a class is a function or
8532 // class that is not a member of the class . . .
8533 if (DC->Equals(CurContext))
8534 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8535
8536 // - There's a scope specifier that does not match any template
8537 // parameter lists, in which case we use some arbitrary context,
8538 // create a method or method template, and wait for instantiation.
8539 // - There's a scope specifier that does match some template
8540 // parameter lists, which we don't handle right now.
8541 } else {
8542 DC = CurContext;
8543 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00008544 }
8545
John McCall29ae6e52010-10-13 05:45:15 +00008546 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00008547 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008548 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8549 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8550 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00008551 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008552 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8553 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00008554 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008555 }
John McCall67d1a672009-08-06 02:15:43 +00008556 }
8557
Douglas Gregor182ddf02009-09-28 00:08:27 +00008558 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00008559 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00008560 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00008561 IsDefinition,
8562 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00008563 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00008564
Douglas Gregor182ddf02009-09-28 00:08:27 +00008565 assert(ND->getDeclContext() == DC);
8566 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00008567
John McCallab88d972009-08-31 22:39:49 +00008568 // Add the function declaration to the appropriate lookup tables,
8569 // adjusting the redeclarations list as necessary. We don't
8570 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00008571 //
John McCallab88d972009-08-31 22:39:49 +00008572 // Also update the scope-based lookup if the target context's
8573 // lookup context is in lexical scope.
8574 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008575 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00008576 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008577 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00008578 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008579 }
John McCall02cace72009-08-28 07:59:38 +00008580
8581 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00008582 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00008583 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00008584 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00008585 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00008586
John McCall337ec3d2010-10-12 23:13:28 +00008587 if (ND->isInvalidDecl())
8588 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00008589 else {
8590 FunctionDecl *FD;
8591 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8592 FD = FTD->getTemplatedDecl();
8593 else
8594 FD = cast<FunctionDecl>(ND);
8595
8596 // Mark templated-scope function declarations as unsupported.
8597 if (FD->getNumTemplateParameterLists())
8598 FrD->setUnsupportedFriend(true);
8599 }
John McCall337ec3d2010-10-12 23:13:28 +00008600
John McCalld226f652010-08-21 09:40:31 +00008601 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00008602}
8603
John McCalld226f652010-08-21 09:40:31 +00008604void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8605 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00008606
Sebastian Redl50de12f2009-03-24 22:27:57 +00008607 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8608 if (!Fn) {
8609 Diag(DelLoc, diag::err_deleted_non_function);
8610 return;
8611 }
8612 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8613 Diag(DelLoc, diag::err_deleted_decl_not_first);
8614 Diag(Prev->getLocation(), diag::note_previous_declaration);
8615 // If the declaration wasn't the first, we delete the function anyway for
8616 // recovery.
8617 }
Sean Hunt10620eb2011-05-06 20:44:56 +00008618 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00008619}
Sebastian Redl13e88542009-04-27 21:33:24 +00008620
Sean Hunte4246a62011-05-12 06:15:49 +00008621void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8622 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8623
8624 if (MD) {
8625 CXXSpecialMember Member = getSpecialMember(MD);
8626 if (Member == CXXInvalid) {
8627 Diag(DefaultLoc, diag::err_default_special_members);
8628 return;
8629 }
8630
8631 MD->setDefaulted();
8632 MD->setExplicitlyDefaulted();
8633
8634 // We'll check it when the record is done
8635 if (MD == MD->getCanonicalDecl())
8636 return;
8637
8638 switch (Member) {
8639 case CXXDefaultConstructor: {
8640 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8641 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008642 if (!CD->isInvalidDecl())
8643 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8644 break;
8645 }
8646
8647 case CXXCopyConstructor: {
8648 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8649 CheckExplicitlyDefaultedCopyConstructor(CD);
8650 if (!CD->isInvalidDecl())
8651 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00008652 break;
8653 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00008654
Sean Hunt2b188082011-05-14 05:23:28 +00008655 case CXXCopyAssignment: {
8656 CheckExplicitlyDefaultedCopyAssignment(MD);
8657 if (!MD->isInvalidDecl())
8658 DefineImplicitCopyAssignment(DefaultLoc, MD);
8659 break;
8660 }
8661
Sean Huntcb45a0f2011-05-12 22:46:25 +00008662 case CXXDestructor: {
8663 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8664 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008665 if (!DD->isInvalidDecl())
8666 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008667 break;
8668 }
8669
Sean Hunte4246a62011-05-12 06:15:49 +00008670 default:
Sean Hunt2b188082011-05-14 05:23:28 +00008671 // FIXME: Do the rest once we have move functions
Sean Hunte4246a62011-05-12 06:15:49 +00008672 break;
8673 }
8674 } else {
8675 Diag(DefaultLoc, diag::err_default_special_members);
8676 }
8677}
8678
Sebastian Redl13e88542009-04-27 21:33:24 +00008679static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00008680 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00008681 Stmt *SubStmt = *CI;
8682 if (!SubStmt)
8683 continue;
8684 if (isa<ReturnStmt>(SubStmt))
8685 Self.Diag(SubStmt->getSourceRange().getBegin(),
8686 diag::err_return_in_constructor_handler);
8687 if (!isa<Expr>(SubStmt))
8688 SearchForReturnInStmt(Self, SubStmt);
8689 }
8690}
8691
8692void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8693 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8694 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8695 SearchForReturnInStmt(*this, Handler);
8696 }
8697}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008698
Mike Stump1eb44332009-09-09 15:08:12 +00008699bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008700 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00008701 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8702 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008703
Chandler Carruth73857792010-02-15 11:53:20 +00008704 if (Context.hasSameType(NewTy, OldTy) ||
8705 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008706 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00008707
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008708 // Check if the return types are covariant
8709 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00008710
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008711 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008712 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8713 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008714 NewClassTy = NewPT->getPointeeType();
8715 OldClassTy = OldPT->getPointeeType();
8716 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008717 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8718 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8719 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8720 NewClassTy = NewRT->getPointeeType();
8721 OldClassTy = OldRT->getPointeeType();
8722 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008723 }
8724 }
Mike Stump1eb44332009-09-09 15:08:12 +00008725
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008726 // The return types aren't either both pointers or references to a class type.
8727 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00008728 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008729 diag::err_different_return_type_for_overriding_virtual_function)
8730 << New->getDeclName() << NewTy << OldTy;
8731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00008732
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008733 return true;
8734 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008735
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008736 // C++ [class.virtual]p6:
8737 // If the return type of D::f differs from the return type of B::f, the
8738 // class type in the return type of D::f shall be complete at the point of
8739 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00008740 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8741 if (!RT->isBeingDefined() &&
8742 RequireCompleteType(New->getLocation(), NewClassTy,
8743 PDiag(diag::err_covariant_return_incomplete)
8744 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008745 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00008746 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008747
Douglas Gregora4923eb2009-11-16 21:35:15 +00008748 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008749 // Check if the new class derives from the old class.
8750 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8751 Diag(New->getLocation(),
8752 diag::err_covariant_return_not_derived)
8753 << New->getDeclName() << NewTy << OldTy;
8754 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8755 return true;
8756 }
Mike Stump1eb44332009-09-09 15:08:12 +00008757
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008758 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00008759 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00008760 diag::err_covariant_return_inaccessible_base,
8761 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8762 // FIXME: Should this point to the return type?
8763 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00008764 // FIXME: this note won't trigger for delayed access control
8765 // diagnostics, and it's impossible to get an undelayed error
8766 // here from access control during the original parse because
8767 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008768 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8769 return true;
8770 }
8771 }
Mike Stump1eb44332009-09-09 15:08:12 +00008772
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008773 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008774 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008775 Diag(New->getLocation(),
8776 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008777 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008778 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8779 return true;
8780 };
Mike Stump1eb44332009-09-09 15:08:12 +00008781
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008782
8783 // The new class type must have the same or less qualifiers as the old type.
8784 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8785 Diag(New->getLocation(),
8786 diag::err_covariant_return_type_class_type_more_qualified)
8787 << New->getDeclName() << NewTy << OldTy;
8788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8789 return true;
8790 };
Mike Stump1eb44332009-09-09 15:08:12 +00008791
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008792 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008793}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008794
Douglas Gregor4ba31362009-12-01 17:24:26 +00008795/// \brief Mark the given method pure.
8796///
8797/// \param Method the method to be marked pure.
8798///
8799/// \param InitRange the source range that covers the "0" initializer.
8800bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00008801 SourceLocation EndLoc = InitRange.getEnd();
8802 if (EndLoc.isValid())
8803 Method->setRangeEnd(EndLoc);
8804
Douglas Gregor4ba31362009-12-01 17:24:26 +00008805 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8806 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00008807 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00008808 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00008809
8810 if (!Method->isInvalidDecl())
8811 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8812 << Method->getDeclName() << InitRange;
8813 return true;
8814}
8815
John McCall731ad842009-12-19 09:28:58 +00008816/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8817/// an initializer for the out-of-line declaration 'Dcl'. The scope
8818/// is a fresh scope pushed for just this purpose.
8819///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008820/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8821/// static data member of class X, names should be looked up in the scope of
8822/// class X.
John McCalld226f652010-08-21 09:40:31 +00008823void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008824 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008825 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008826
John McCall731ad842009-12-19 09:28:58 +00008827 // We should only get called for declarations with scope specifiers, like:
8828 // int foo::bar;
8829 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008830 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008831}
8832
8833/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00008834/// initializer for the out-of-line declaration 'D'.
8835void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008836 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008837 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008838
John McCall731ad842009-12-19 09:28:58 +00008839 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008840 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008841}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008842
8843/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8844/// C++ if/switch/while/for statement.
8845/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00008846DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008847 // C++ 6.4p2:
8848 // The declarator shall not specify a function or an array.
8849 // The type-specifier-seq shall not contain typedef and shall not declare a
8850 // new class or enumeration.
8851 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8852 "Parser allowed 'typedef' as storage class of condition decl.");
8853
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008854 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00008855 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
8856 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008857
8858 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
8859 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
8860 // would be created and CXXConditionDeclExpr wants a VarDecl.
8861 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
8862 << D.getSourceRange();
8863 return DeclResult();
8864 } else if (OwnedTag && OwnedTag->isDefinition()) {
8865 // The type-specifier-seq shall not declare a new class or enumeration.
8866 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
8867 }
8868
John McCalld226f652010-08-21 09:40:31 +00008869 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008870 if (!Dcl)
8871 return DeclResult();
8872
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008873 return Dcl;
8874}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008875
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008876void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8877 bool DefinitionRequired) {
8878 // Ignore any vtable uses in unevaluated operands or for classes that do
8879 // not have a vtable.
8880 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8881 CurContext->isDependentContext() ||
8882 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00008883 return;
8884
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008885 // Try to insert this class into the map.
8886 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8887 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8888 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8889 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00008890 // If we already had an entry, check to see if we are promoting this vtable
8891 // to required a definition. If so, we need to reappend to the VTableUses
8892 // list, since we may have already processed the first entry.
8893 if (DefinitionRequired && !Pos.first->second) {
8894 Pos.first->second = true;
8895 } else {
8896 // Otherwise, we can early exit.
8897 return;
8898 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008899 }
8900
8901 // Local classes need to have their virtual members marked
8902 // immediately. For all other classes, we mark their virtual members
8903 // at the end of the translation unit.
8904 if (Class->isLocalClass())
8905 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00008906 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008907 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00008908}
8909
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008910bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008911 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00008912 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00008913
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008914 // Note: The VTableUses vector could grow as a result of marking
8915 // the members of a class as "used", so we check the size each
8916 // time through the loop and prefer indices (with are stable) to
8917 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00008918 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008919 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00008920 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008921 if (!Class)
8922 continue;
8923
8924 SourceLocation Loc = VTableUses[I].second;
8925
8926 // If this class has a key function, but that key function is
8927 // defined in another translation unit, we don't need to emit the
8928 // vtable even though we're using it.
8929 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00008930 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008931 switch (KeyFunction->getTemplateSpecializationKind()) {
8932 case TSK_Undeclared:
8933 case TSK_ExplicitSpecialization:
8934 case TSK_ExplicitInstantiationDeclaration:
8935 // The key function is in another translation unit.
8936 continue;
8937
8938 case TSK_ExplicitInstantiationDefinition:
8939 case TSK_ImplicitInstantiation:
8940 // We will be instantiating the key function.
8941 break;
8942 }
8943 } else if (!KeyFunction) {
8944 // If we have a class with no key function that is the subject
8945 // of an explicit instantiation declaration, suppress the
8946 // vtable; it will live with the explicit instantiation
8947 // definition.
8948 bool IsExplicitInstantiationDeclaration
8949 = Class->getTemplateSpecializationKind()
8950 == TSK_ExplicitInstantiationDeclaration;
8951 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
8952 REnd = Class->redecls_end();
8953 R != REnd; ++R) {
8954 TemplateSpecializationKind TSK
8955 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
8956 if (TSK == TSK_ExplicitInstantiationDeclaration)
8957 IsExplicitInstantiationDeclaration = true;
8958 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8959 IsExplicitInstantiationDeclaration = false;
8960 break;
8961 }
8962 }
8963
8964 if (IsExplicitInstantiationDeclaration)
8965 continue;
8966 }
8967
8968 // Mark all of the virtual members of this class as referenced, so
8969 // that we can build a vtable. Then, tell the AST consumer that a
8970 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00008971 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008972 MarkVirtualMembersReferenced(Loc, Class);
8973 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8974 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
8975
8976 // Optionally warn if we're emitting a weak vtable.
8977 if (Class->getLinkage() == ExternalLinkage &&
8978 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00008979 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008980 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
8981 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008982 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008983 VTableUses.clear();
8984
Douglas Gregor78844032011-04-22 22:25:37 +00008985 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008986}
Anders Carlssond6a637f2009-12-07 08:24:59 +00008987
Rafael Espindola3e1ae932010-03-26 00:36:59 +00008988void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
8989 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00008990 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
8991 e = RD->method_end(); i != e; ++i) {
8992 CXXMethodDecl *MD = *i;
8993
8994 // C++ [basic.def.odr]p2:
8995 // [...] A virtual member function is used if it is not pure. [...]
8996 if (MD->isVirtual() && !MD->isPure())
8997 MarkDeclarationReferenced(Loc, MD);
8998 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00008999
9000 // Only classes that have virtual bases need a VTT.
9001 if (RD->getNumVBases() == 0)
9002 return;
9003
9004 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9005 e = RD->bases_end(); i != e; ++i) {
9006 const CXXRecordDecl *Base =
9007 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009008 if (Base->getNumVBases() == 0)
9009 continue;
9010 MarkVirtualMembersReferenced(Loc, Base);
9011 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00009012}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009013
9014/// SetIvarInitializers - This routine builds initialization ASTs for the
9015/// Objective-C implementation whose ivars need be initialized.
9016void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9017 if (!getLangOptions().CPlusPlus)
9018 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00009019 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009020 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9021 CollectIvarsToConstructOrDestruct(OID, ivars);
9022 if (ivars.empty())
9023 return;
Sean Huntcbb67482011-01-08 20:30:50 +00009024 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009025 for (unsigned i = 0; i < ivars.size(); i++) {
9026 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009027 if (Field->isInvalidDecl())
9028 continue;
9029
Sean Huntcbb67482011-01-08 20:30:50 +00009030 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009031 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9032 InitializationKind InitKind =
9033 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9034
9035 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009036 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00009037 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00009038 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009039 // Note, MemberInit could actually come back empty if no initialization
9040 // is required (e.g., because it would call a trivial default constructor)
9041 if (!MemberInit.get() || MemberInit.isInvalid())
9042 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00009043
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009044 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00009045 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9046 SourceLocation(),
9047 MemberInit.takeAs<Expr>(),
9048 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009049 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009050
9051 // Be sure that the destructor is accessible and is marked as referenced.
9052 if (const RecordType *RecordTy
9053 = Context.getBaseElementType(Field->getType())
9054 ->getAs<RecordType>()) {
9055 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00009056 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009057 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9058 CheckDestructorAccess(Field->getLocation(), Destructor,
9059 PDiag(diag::err_access_dtor_ivar)
9060 << Context.getBaseElementType(Field->getType()));
9061 }
9062 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009063 }
9064 ObjCImplementation->setIvarInitializers(Context,
9065 AllToInit.data(), AllToInit.size());
9066 }
9067}
Sean Huntfe57eef2011-05-04 05:57:24 +00009068
Sean Huntebcbe1d2011-05-04 23:29:54 +00009069static
9070void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9071 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9072 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9073 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9074 Sema &S) {
9075 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9076 CE = Current.end();
9077 if (Ctor->isInvalidDecl())
9078 return;
9079
9080 const FunctionDecl *FNTarget = 0;
9081 CXXConstructorDecl *Target;
9082
9083 // We ignore the result here since if we don't have a body, Target will be
9084 // null below.
9085 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9086 Target
9087= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9088
9089 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9090 // Avoid dereferencing a null pointer here.
9091 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9092
9093 if (!Current.insert(Canonical))
9094 return;
9095
9096 // We know that beyond here, we aren't chaining into a cycle.
9097 if (!Target || !Target->isDelegatingConstructor() ||
9098 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9099 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9100 Valid.insert(*CI);
9101 Current.clear();
9102 // We've hit a cycle.
9103 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9104 Current.count(TCanonical)) {
9105 // If we haven't diagnosed this cycle yet, do so now.
9106 if (!Invalid.count(TCanonical)) {
9107 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00009108 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00009109 << Ctor;
9110
9111 // Don't add a note for a function delegating directo to itself.
9112 if (TCanonical != Canonical)
9113 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9114
9115 CXXConstructorDecl *C = Target;
9116 while (C->getCanonicalDecl() != Canonical) {
9117 (void)C->getTargetConstructor()->hasBody(FNTarget);
9118 assert(FNTarget && "Ctor cycle through bodiless function");
9119
9120 C
9121 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9122 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9123 }
9124 }
9125
9126 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9127 Invalid.insert(*CI);
9128 Current.clear();
9129 } else {
9130 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9131 }
9132}
9133
9134
Sean Huntfe57eef2011-05-04 05:57:24 +00009135void Sema::CheckDelegatingCtorCycles() {
9136 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9137
Sean Huntebcbe1d2011-05-04 23:29:54 +00009138 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9139 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00009140
9141 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Sean Huntebcbe1d2011-05-04 23:29:54 +00009142 I = DelegatingCtorDecls.begin(),
9143 E = DelegatingCtorDecls.end();
9144 I != E; ++I) {
9145 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00009146 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00009147
9148 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9149 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00009150}