blob: 8bf7cb67b88a409a352294453081d14ecf4fe4d3 [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000036#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000037#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner58258242008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000055
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 public:
Mike Stump11289f42009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 };
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000071 }
72
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 }
Chris Lattner58258242008-04-10 02:22:51 +000099
Douglas Gregor8e12c382008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000102
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111 }
Chris Lattner58258242008-04-10 02:22:51 +0000112}
113
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Alexis Hunt6d5b96c2011-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) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000150 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-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)
Alexis Hunt913820d2011-05-13 06:10:58 +0000174 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 Exceptions.push_back(*E);
176}
177
Anders Carlssonc80a1272009-08-25 02:29:20 +0000178bool
John McCallb268a282010-08-23 23:25:46 +0000179Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000180 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000193 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
194 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000195 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
196 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000197 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000198 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000199 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000200 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000201 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000202 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000203
John McCallacf0ee52010-10-08 02:01:28 +0000204 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000205 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000206
Anders Carlssonc80a1272009-08-25 02:29:20 +0000207 // Okay: add the default argument to the parameter
208 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000209
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000222 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000223}
224
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000228void
John McCall48871652010-08-21 09:40:31 +0000229Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000230 Expr *DefaultArg) {
231 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000232 return;
Mike Stump11289f42009-09-09 15:08:12 +0000233
John McCall48871652010-08-21 09:40:31 +0000234 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000235 UnparsedDefaultArgLocs.erase(Param);
236
Chris Lattner199abbc2008-04-08 05:04:30 +0000237 // Default arguments are only permitted in C++
238 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000239 Diag(EqualLoc, diag::err_param_default_argument)
240 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000241 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000242 return;
243 }
244
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000251 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000252 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
253 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000254 Param->setInvalidDecl();
255 return;
256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
John McCallb268a282010-08-23 23:25:46 +0000258 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000259}
260
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000265void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000266 SourceLocation EqualLoc,
267 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000268 if (!param)
269 return;
Mike Stump11289f42009-09-09 15:08:12 +0000270
John McCall48871652010-08-21 09:40:31 +0000271 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000272 if (Param)
273 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlsson84613c42009-06-12 16:51:40 +0000275 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000276}
277
Douglas Gregor4d87df52008-12-16 21:30:33 +0000278/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
279/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000280void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000281 if (!param)
282 return;
Mike Stump11289f42009-09-09 15:08:12 +0000283
John McCall48871652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Anders Carlsson84613c42009-06-12 16:51:40 +0000286 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000287
Anders Carlsson84613c42009-06-12 16:51:40 +0000288 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000289}
290
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000304 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000305 DeclaratorChunk &chunk = D.getTypeObject(i);
306 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000307 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
308 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000309 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000310 if (Param->hasUnparsedDefaultArg()) {
311 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000320 }
321 }
322 }
323 }
324}
325
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000333 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000355 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000356
Francois Pichet53fe2bb2011-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 Pichet8cb243a2011-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 Pichet93921652011-04-22 08:25:24 +0000373 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000374 Invalid = false;
375 }
376 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000377
Francois Pichet8cb243a2011-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 Gregor08dc5842010-01-13 00:12:48 +0000383 // int f(int);
384 // void g(int (*fp)(int) = f);
385 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000386 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000387 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor4f15f4d2009-09-17 19:51:30 +0000401 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000404 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000405 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000406 if (OldParam->hasUninstantiatedDefaultArg())
407 NewParam->setUninstantiatedDefaultArg(
408 OldParam->getUninstantiatedDefaultArg());
409 else
John McCalle61b02b2010-05-04 01:53:42 +0000410 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000461 }
462 }
463
Douglas Gregorf40863c2010-02-12 07:32:17 +0000464 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000465 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000466
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000467 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000468}
469
Sebastian Redlfa453cf2011-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 Lattner199abbc2008-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 Carlsson5a532382009-08-25 01:23:32 +0000522 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000533 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000534 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000535 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000536 if (Param->isInvalidDecl())
537 /* We already complained about this parameter. */;
538 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000539 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000540 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000541 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000542 else
Mike Stump11289f42009-09-09 15:08:12 +0000543 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000544 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000557 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000558 Param->setDefaultArg(0);
559 }
560 }
561 }
562}
Douglas Gregor556877c2008-04-13 21:30:24 +0000563
Douglas Gregor61956c42008-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 Kyrtzidis32a03792008-11-08 16:45:02 +0000568bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
569 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000570 assert(getLangOptions().CPlusPlus && "No class names in C!");
571
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000572 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000573 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000574 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-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 Gregor1aa3edb2010-02-05 06:12:42 +0000579 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000580 return &II == CurDecl->getIdentifier();
581 else
582 return false;
583}
584
Mike Stump11289f42009-09-09 15:08:12 +0000585/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-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 Gregor752a5952011-01-03 22:36:02 +0000593 TypeSourceInfo *TInfo,
594 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000595 QualType BaseType = TInfo->getType();
596
Douglas Gregor463421d2009-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 Gregor752a5952011-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 Gregor463421d2009-03-03 04:44:36 +0000612 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000613 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000614 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000615 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000616
617 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000635 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000636 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000637 << SpecifierRange)) {
638 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000639 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000640 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000641
Eli Friedmanc96d4962009-08-15 21:55:26 +0000642 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000643 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000645 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000646 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000647 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
648 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000649
Anders Carlsson65c76d32011-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 Carlsson1eb95962011-01-24 16:26:15 +0000653 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-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 McCall3696dcb2010-08-17 07:23:57 +0000661 if (BaseDecl->isInvalidDecl())
662 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000663
664 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000665 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000666 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000667 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000668}
669
Douglas Gregor556877c2008-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 Stump11289f42009-09-09 15:08:12 +0000672/// example:
673/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000674/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000675BaseResult
John McCall48871652010-08-21 09:40:31 +0000676Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000677 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000678 ParsedType basetype, SourceLocation BaseLoc,
679 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000680 if (!classdecl)
681 return true;
682
Douglas Gregorc40290e2009-03-09 23:48:35 +0000683 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000684 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000685 if (!Class)
686 return true;
687
Nick Lewycky19b9f952010-07-26 16:56:01 +0000688 TypeSourceInfo *TInfo = 0;
689 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000690
Douglas Gregor752a5952011-01-03 22:36:02 +0000691 if (EllipsisLoc.isInvalid() &&
692 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000693 UPPC_BaseType))
694 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000695
Douglas Gregor463421d2009-03-03 04:44:36 +0000696 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000697 Virtual, Access, TInfo,
698 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000699 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000700
Douglas Gregor463421d2009-03-03 04:44:36 +0000701 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000702}
Douglas Gregor556877c2008-04-13 21:30:24 +0000703
Douglas Gregor463421d2009-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 Gregor29a92472008-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 Gregor9d6290b2008-10-23 18:13:27 +0000713 // that the key is always the unqualified canonical type of the base
714 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000715 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
716
717 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000718 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000719 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000720 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000721 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000722 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000723 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-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 Gregor29a92472008-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 Gregor463421d2009-03-03 04:44:36 +0000735 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000736 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000737 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000738 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000739
740 // Delete the duplicate base class specifier; we're going to
741 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000742 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000743
744 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000745 } else {
746 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000747 KnownBaseTypes[NewBaseType] = Bases[idx];
748 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000749 }
750 }
751
752 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000753 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-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 Gregorb77af8f2009-07-22 20:55:49 +0000758 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-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 McCall48871652010-08-21 09:40:31 +0000766void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000767 unsigned NumBases) {
768 if (!ClassDecl || !Bases || !NumBases)
769 return;
770
771 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000772 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000773 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000774}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000775
John McCalle78aac42010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000790
791 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
792 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000793 return false;
794
John McCalle78aac42010-03-10 03:28:59 +0000795 CXXRecordDecl *BaseRD = GetClassForType(Base);
796 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000797 return false;
798
John McCall67da35c2010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000809 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
810 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000811 return false;
812
John McCalle78aac42010-03-10 03:28:59 +0000813 CXXRecordDecl *BaseRD = GetClassForType(Base);
814 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000815 return false;
816
Douglas Gregor36d1b142009-10-06 17:59:45 +0000817 return DerivedRD->isDerivedFrom(BaseRD, Paths);
818}
819
Anders Carlssona70cff62010-04-24 19:06:50 +0000820void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000821 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-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 McCallcf142162010-08-07 06:22:56 +0000840 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000841}
842
Douglas Gregor88d292c2010-05-13 16:44:06 +0000843/// \brief Determine whether the given base path includes a virtual
844/// base class.
John McCallcf142162010-08-07 06:22:56 +0000845bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
846 for (CXXCastPath::const_iterator B = BasePath.begin(),
847 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000848 B != BEnd; ++B)
849 if ((*B)->isVirtual())
850 return true;
851
852 return false;
853}
854
Douglas Gregor36d1b142009-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 McCall1064d7e2010-03-16 05:22:47 +0000865 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000866 unsigned AmbigiousBaseConvID,
867 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000868 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000869 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-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 Carlssona70cff62010-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 Carlsson7afe4242010-04-24 17:11:09 +0000892 }
John McCall5b0829a2010-02-10 09:31:12 +0000893 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000894
895 // Build a base path if necessary.
896 if (BasePath)
897 BuildBasePathArray(Paths, *BasePath);
898 return false;
Douglas Gregor36d1b142009-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 Redl7c353682009-11-14 21:15:49 +0000926 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000927 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000928 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000929 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000930 IgnoreAccess ? 0
931 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000932 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000933 Loc, Range, DeclarationName(),
934 BasePath);
Douglas Gregor36d1b142009-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 Kyrtzidised983422008-07-01 10:37:29 +0000969//===----------------------------------------------------------------------===//
970// C++ class member Handling
971//===----------------------------------------------------------------------===//
972
Abramo Bagnarad7340582010-06-05 05:09:32 +0000973/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000974Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
975 SourceLocation ASLoc,
976 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000977 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000978 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000979 ASLoc, ColonLoc);
980 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000981 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000982}
983
Anders Carlssonfd835532011-01-20 05:57:14 +0000984/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000985void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000986 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
987 if (!MD || !MD->isVirtual())
988 return;
989
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000990 if (MD->isDependentContext())
991 return;
992
Anders Carlssonfd835532011-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 Carlsson1eb95962011-01-24 16:26:15 +0000999 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001000 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001001 diag::err_function_marked_override_not_overriding)
1002 << MD->getDeclName();
1003 return;
1004 }
1005}
1006
Anders Carlsson3f610c72011-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 Carlsson1eb95962011-01-24 16:26:15 +00001012 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-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 Carlsson3f610c72011-01-20 16:25:36 +00001019}
1020
Argyrios Kyrtzidised983422008-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 Lattnereb4373d2009-04-12 22:37:57 +00001024/// any.
John McCall48871652010-08-21 09:40:31 +00001025Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001026Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001027 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +00001028 ExprTy *BW, const VirtSpecifiers &VS,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001029 ExprTy *InitExpr, bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001030 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001031 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1032 DeclarationName Name = NameInfo.getName();
1033 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-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 Kyrtzidised983422008-07-01 10:37:29 +00001039 Expr *BitWidth = static_cast<Expr*>(BW);
1040 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001041
John McCallb1cd7da2010-06-04 08:34:12 +00001042 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001043 assert(!DS.isFriendSpecified());
1044
John McCallb1cd7da2010-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 McCallba7bf592010-08-24 05:47:05 +00001050 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +00001051 isFunc = TDType->isFunctionType();
1052 }
1053
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-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 Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +00001065 case DeclSpec::SCS_mutable:
1066 if (isFunc) {
1067 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001068 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001069 else
Chris Lattner3b054132008-11-19 05:08:23 +00001070 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001071
Sebastian Redl8071edb2008-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 Redlccdfaba2008-11-14 23:42:31 +00001074 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001075 }
1076 break;
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +00001086 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1087 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001088 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001089
1090 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001091 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001092 CXXScopeSpec &SS = D.getCXXScopeSpec();
1093
Douglas Gregora007d362010-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 Gregor3447e762009-08-20 22:52:58 +00001112 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001113 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001114 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1115 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001116 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001117 } else {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001118 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001119 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001120 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001121 }
Chris Lattnerd26760a2009-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 Gregor212cab32009-03-11 20:22:50 +00001127 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-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 Stump11289f42009-09-09 15:08:12 +00001140 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001141 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001142 }
Mike Stump11289f42009-09-09 15:08:12 +00001143
Chris Lattnerd26760a2009-03-05 23:01:03 +00001144 BitWidth = 0;
1145 Member->setInvalidDecl();
1146 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001147
1148 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregor3447e762009-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 Lattner73bf7b42009-03-05 22:45:59 +00001154 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001155
Anders Carlsson13a69102011-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 Carlssonfd835532011-01-20 05:57:14 +00001162 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001163 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-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 Carlssonfd835532011-01-20 05:57:14 +00001171 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001172 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001173 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001174
Douglas Gregorf2f08062011-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 Carlssonc87f8612011-01-20 06:29:02 +00001181 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001182
Douglas Gregor92751d42008-11-17 22:58:34 +00001183 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001184
Douglas Gregor0c880302009-03-11 23:00:04 +00001185 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001186 AddInitializerToDecl(Member, Init, false,
1187 DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001188
Richard Smithb2bc2e62011-02-21 20:05:19 +00001189 FinalizeDeclaration(Member);
1190
John McCall25849ca2011-02-15 07:12:36 +00001191 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001192 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001193 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001194}
1195
Douglas Gregor15e77a22009-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 Gregore8381c02008-11-05 04:29:56 +00001241/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001242MemInitResult
John McCall48871652010-08-21 09:40:31 +00001243Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001244 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001245 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001246 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001247 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001248 SourceLocation IdLoc,
1249 SourceLocation LParenLoc,
1250 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001251 SourceLocation RParenLoc,
1252 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001253 if (!ConstructorD)
1254 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001255
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001256 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001257
1258 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001259 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-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 Lewycky9331ed82010-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 Gregore8381c02008-11-05 04:29:56 +00001278 // mem-initializer-id for the hidden base class may be specified
1279 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001280 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001281 // Look for a member, first.
1282 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001283 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001284 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001285 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001286 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001287
Douglas Gregor44e7df62011-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 Pichetd583da02010-12-04 09:14:42 +00001293 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001294 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001295 }
1296
Francois Pichetd583da02010-12-04 09:14:42 +00001297 // Handle anonymous union case.
1298 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-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 Pichetd583da02010-12-04 09:14:42 +00001304 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1305 NumArgs, IdLoc,
1306 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001307 }
Francois Pichetd583da02010-12-04 09:14:42 +00001308 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001309 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001310 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001311 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001312 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001313
1314 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001315 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-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 McCallda6841b2010-04-09 19:01:14 +00001324 // We don't want access-control diagnostics here.
1325 R.suppressDiagnostics();
1326
Douglas Gregora3b624a2010-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 Gregor9cbc22b2011-02-28 22:42:13 +00001336 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1337 SS.getWithLocInContext(Context),
1338 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001339 if (BaseType.isNull())
1340 return true;
1341
Douglas Gregora3b624a2010-01-19 06:46:48 +00001342 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001343 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001344 }
1345 }
1346
Douglas Gregor15e77a22009-12-31 09:10:24 +00001347 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001348 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001349 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1350 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001351 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001352 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001358 << FixItHint::CreateReplacement(R.getNameLoc(),
1359 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001360 Diag(Member->getLocation(), diag::note_previous_decl)
1361 << Member->getDeclName();
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001377 << FixItHint::CreateReplacement(R.getNameLoc(),
1378 R.getLookupName().getAsString());
Douglas Gregor43a08572010-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 Gregor15e77a22009-12-31 09:10:24 +00001387 TyD = Type;
1388 }
1389 }
1390 }
1391
Douglas Gregora3b624a2010-01-19 06:46:48 +00001392 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-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 McCallb5a0d312009-12-21 10:41:20 +00001397 }
1398
Douglas Gregora3b624a2010-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 McCallb5a0d312009-12-21 10:41:20 +00001404
Douglas Gregora3b624a2010-01-19 06:46:48 +00001405 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001406 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001407 }
John McCallb5a0d312009-12-21 10:41:20 +00001408 }
1409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
John McCallbcd03502009-12-07 02:54:59 +00001411 if (!TInfo)
1412 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001413
John McCallbcd03502009-12-07 02:54:59 +00001414 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001415 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001416}
1417
John McCalle22a04a2009-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 Lewyckya2fb98b2010-06-15 07:32:55 +00001422static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001423 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001424 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001425 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1426
Nick Lewyckya2fb98b2010-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 Carlsson0f7e94f2010-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 Lewycky300524242010-10-06 18:37:39 +00001442 (void)VD;
Anders Carlsson0f7e94f2010-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 McCalle22a04a2009-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 Lewyckya2fb98b2010-06-15 07:32:55 +00001456 const Expr *base = ME->getBase();
John McCalle22a04a2009-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 Collingbournee190dee2011-03-11 19:24:49 +00001466 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-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 McCalle22a04a2009-11-04 23:02:40 +00001474 }
John McCall8322c3a2011-02-13 04:07:26 +00001475 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001476 if (!*it) {
1477 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001478 continue;
1479 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001480 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1481 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001482 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001483 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001484}
1485
John McCallfaf5fb42010-08-26 23:41:50 +00001486MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001487Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001488 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001489 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001490 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001491 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1492 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1493 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001494 "Member must be a FieldDecl or IndirectFieldDecl");
1495
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001496 if (Member->isInvalidDecl())
1497 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001498
John McCalle22a04a2009-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 McCallc90f6d72009-11-04 23:13:52 +00001502 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-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 Friedman8e1433b2009-07-29 19:44:27 +00001516 bool HasDependentArg = false;
1517 for (unsigned i = 0; i < NumArgs; i++)
1518 HasDependentArg |= Args[i]->isTypeDependent();
1519
Chandler Carruthd44c3102010-12-06 09:23:57 +00001520 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001521 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-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 Carruthd44c3102010-12-06 09:23:57 +00001524 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1525 RParenLoc);
Douglas Gregor7ae2d772010-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 Carruthd44c3102010-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 McCallacf0ee52010-10-08 02:01:28 +00001540
Chandler Carruthd44c3102010-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 Gregora40433a2010-12-07 00:41:46 +00001554 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-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 Gregor7ae2d772010-01-31 09:12:51 +00001570 }
1571
Chandler Carruthd44c3102010-12-06 09:23:57 +00001572 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001573 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001574 IdLoc, LParenLoc, Init,
1575 RParenLoc);
1576 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001577 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001578 IdLoc, LParenLoc, Init,
1579 RParenLoc);
1580 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001581}
1582
John McCallfaf5fb42010-08-26 23:41:50 +00001583MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001584Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1585 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001586 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001587 SourceLocation LParenLoc,
1588 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001589 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-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 Redl9cb4be22011-03-12 13:53:51 +00001594
Alexis Huntc5575cc2011-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());
Alexis Hunt6118d662011-05-04 05:57:24 +00001610 CXXConstructorDecl *Constructor
1611 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-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);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001642}
1643
1644MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001645Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001646 Expr **Args, unsigned NumArgs,
1647 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001648 CXXRecordDecl *ClassDecl,
1649 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001650 bool HasDependentArg = false;
1651 for (unsigned i = 0; i < NumArgs; i++)
1652 HasDependentArg |= Args[i]->isTypeDependent();
1653
Douglas Gregor1c69bf02010-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 Lewycky9331ed82010-11-20 01:29:55 +00001663 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-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 Gregor44e7df62011-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 Gregor1c69bf02010-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) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001691 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1692 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001693 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1694 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001695
Douglas Gregor1c69bf02010-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 Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001721 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001722 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1723 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001724
Douglas Gregor7ae2d772010-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 Stump11289f42009-09-09 15:08:12 +00001731
Alexis Hunt1d792652011-01-08 20:30:50 +00001732 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001733 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001734 LParenLoc,
1735 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001736 RParenLoc,
1737 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001738 }
Douglas Gregor7ae2d772010-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 Bagnara1108e7b2010-05-20 10:00:11 +00001746 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-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 Carlsson43c64af2010-04-21 19:52:01 +00001755 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001761 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001762 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001763 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001764 if (BaseInit.isInvalid())
1765 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001766
1767 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-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 Gregora40433a2010-12-07 00:41:46 +00001772 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001784 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001785 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1786 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001787 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001788 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001789 LParenLoc,
1790 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001791 RParenLoc,
1792 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001793 }
1794
Alexis Hunt1d792652011-01-08 20:30:50 +00001795 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001796 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001797 LParenLoc,
1798 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001799 RParenLoc,
1800 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001801}
1802
Anders Carlsson1b00e242010-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 Carlsson6bd91c32010-04-23 02:00:02 +00001811static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001812BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001813 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001814 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001815 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001816 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001817 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001818 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1819 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001820
John McCalldadc5752010-08-24 06:29:42 +00001821 ExprResult BaseInit;
Anders Carlsson1b00e242010-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 McCallfaf5fb42010-08-26 23:41:50 +00001829 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001830 break;
1831 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001832
Anders Carlsson1b00e242010-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 Gregorea972d32011-02-28 21:54:11 +00001838 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001839 Constructor->getLocation(), ParamType,
1840 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001841
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001842 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001843 QualType ArgTy =
1844 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1845 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001846
1847 CXXCastPath BasePath;
1848 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001849 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1850 CK_UncheckedDerivedToBase,
1851 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001852
Anders Carlsson1b00e242010-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 McCallfaf5fb42010-08-26 23:41:50 +00001859 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001860 break;
1861 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001862
Anders Carlsson1b00e242010-04-23 03:10:23 +00001863 case IIK_Move:
1864 assert(false && "Unhandled initializer kind!");
1865 }
John McCallb268a282010-08-23 23:25:46 +00001866
Douglas Gregora40433a2010-12-07 00:41:46 +00001867 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001868 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001869 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001870
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001871 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001872 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001873 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1874 SourceLocation()),
1875 BaseSpec->isVirtual(),
1876 SourceLocation(),
1877 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001878 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001879 SourceLocation());
1880
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001881 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001882}
1883
Anders Carlsson3c1db572010-04-23 02:15:47 +00001884static bool
1885BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001886 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001887 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001888 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001889 if (Field->isInvalidDecl())
1890 return true;
1891
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001892 SourceLocation Loc = Constructor->getLocation();
1893
Anders Carlsson423f5d82010-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 Gregorea972d32011-02-28 21:54:11 +00001899 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001900 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-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 McCalldadc5752010-08-24 06:29:42 +00001908 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001909 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-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 Carlsson423f5d82010-04-23 16:04:08 +00001917 return true;
1918
Douglas Gregor94f9a482010-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 Bagnaradff19302011-03-08 08:55:46 +00001937 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001938 IterationVarName, SizeType,
1939 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001940 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001941 IndexVariables.push_back(IterationVar);
1942
1943 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001944 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001945 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-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 McCallb268a282010-08-23 23:25:46 +00001950 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001951 Loc,
John McCallb268a282010-08-23 23:25:46 +00001952 IterationVarRef.take(),
Douglas Gregor94f9a482010-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 McCalldadc5752010-08-24 06:29:42 +00001979 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001980 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001981 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001982 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001983 if (MemberInit.isInvalid())
1984 return true;
1985
1986 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001987 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001988 MemberInit.takeAs<Expr>(), Loc,
1989 IndexVariables.data(),
1990 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001991 return false;
1992 }
1993
Anders Carlsson423f5d82010-04-23 16:04:08 +00001994 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1995
Anders Carlsson3c1db572010-04-23 02:15:47 +00001996 QualType FieldBaseElementType =
1997 SemaRef.Context.getBaseElementType(Field->getType());
1998
Anders Carlsson3c1db572010-04-23 02:15:47 +00001999 if (FieldBaseElementType->isRecordType()) {
2000 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002001 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002002 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002003
2004 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002005 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002006 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002007
Douglas Gregora40433a2010-12-07 00:41:46 +00002008 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002009 if (MemberInit.isInvalid())
2010 return true;
2011
2012 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002013 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002014 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002015 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002016 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002017 return false;
2018 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002019
Alexis Hunt8b455182011-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 Carlssondca6be02010-04-23 03:07:47 +00002030
Alexis Hunt8b455182011-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 Carlssondca6be02010-04-23 03:07:47 +00002040 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002041
2042 // Nothing to initialize.
2043 CXXMemberInit = 0;
2044 return false;
2045}
John McCallbc83b3f2010-05-20 23:23:51 +00002046
2047namespace {
2048struct BaseAndFieldInfo {
2049 Sema &S;
2050 CXXConstructorDecl *Ctor;
2051 bool AnyErrorsInInits;
2052 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002053 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2054 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-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 Carruth139e9622010-06-30 02:59:29 +00002070 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002071 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002072 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-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 McCallbc83b3f2010-05-20 23:23:51 +00002079 CXXRecordDecl *FieldClassDecl
2080 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-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++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002091 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002092 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-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 Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002097 } else if ((*FA)->isAnonymousStructOrUnion()) {
2098 if (CollectFieldInitializer(Info, Top, *FA))
2099 return true;
Chandler Carruth139e9622010-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 McCallbc83b3f2010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00002125 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002126 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2127 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002128
Francois Pichetd583da02010-12-04 09:14:42 +00002129 if (Init)
2130 Info.AllToInit.push_back(Init);
2131
John McCallbc83b3f2010-05-20 23:23:51 +00002132 return false;
2133}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002134
2135bool
2136Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2137 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002138 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-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
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002145 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2146 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2147 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2148 }
2149
Alexis Hunte2622992011-05-05 00:05:47 +00002150 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002151
Alexis Hunt61bc1732011-05-01 07:04:31 +00002152 return false;
2153}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002154
Eli Friedman9cf6b592009-11-09 19:20:36 +00002155bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002156Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2157 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002158 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002159 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002160 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002161 // Just store the initializers as written, they will be checked during
2162 // instantiation.
2163 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002164 Constructor->setNumCtorInitializers(NumInitializers);
2165 CXXCtorInitializer **baseOrMemberInitializers =
2166 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002167 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002168 NumInitializers * sizeof(CXXCtorInitializer*));
2169 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002170 }
2171
2172 return false;
2173 }
2174
John McCallbc83b3f2010-05-20 23:23:51 +00002175 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002176
Fariborz Jahanian3501bce2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00002179 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002180 if (!ClassDecl)
2181 return true;
2182
Eli Friedman9cf6b592009-11-09 19:20:36 +00002183 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002184
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002185 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002186 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002187
2188 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002189 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002190 else
Francois Pichetd583da02010-12-04 09:14:42 +00002191 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002192 }
2193
Anders Carlsson43c64af2010-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 Carlssondb0a9652010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00002206 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002207 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2208 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002209 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002210 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002211 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002212 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002213 VBase, IsInheritedVirtualBase,
2214 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002215 HadError = true;
2216 continue;
2217 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002218
John McCallbc83b3f2010-05-20 23:23:51 +00002219 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002220 }
2221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
John McCallbc83b3f2010-05-20 23:23:51 +00002223 // Non-virtual bases.
Anders Carlssondb0a9652010-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 Stump11289f42009-09-09 15:08:12 +00002229
Alexis Hunt1d792652011-01-08 20:30:50 +00002230 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002231 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2232 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002233 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002234 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002235 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002236 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002237 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002238 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002239 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002240 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002241
John McCallbc83b3f2010-05-20 23:23:51 +00002242 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002243 }
2244 }
Mike Stump11289f42009-09-09 15:08:12 +00002245
John McCallbc83b3f2010-05-20 23:23:51 +00002246 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002247 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-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 McCallbc83b3f2010-05-20 23:23:51 +00002254 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002255 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002256 }
Mike Stump11289f42009-09-09 15:08:12 +00002257
John McCallbc83b3f2010-05-20 23:23:51 +00002258 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002259 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002260 Constructor->setNumCtorInitializers(NumInitializers);
2261 CXXCtorInitializer **baseOrMemberInitializers =
2262 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002263 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002264 NumInitializers * sizeof(CXXCtorInitializer*));
2265 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002266
John McCalla6309952010-03-16 21:39:52 +00002267 // Constructors implicitly reference the base and member
2268 // destructors.
2269 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2270 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002271 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002272
2273 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002274}
2275
Eli Friedman952c15d2009-07-21 19:28:10 +00002276static void *GetKeyForTopLevelField(FieldDecl *Field) {
2277 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002278 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00002285static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002286 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002287}
2288
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002289static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002290 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002291 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002292 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002293
Eli Friedman952c15d2009-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 Pichetd583da02010-12-04 09:14:42 +00002296 FieldDecl *Field = Member->getAnyMember();
2297
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00002300 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00002310 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002311 }
Mike Stump11289f42009-09-09 15:08:12 +00002312
Anders Carlssona942dcd2010-03-30 15:39:27 +00002313 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002314}
2315
Anders Carlssone857b292010-04-02 03:37:03 +00002316static void
2317DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002318 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002319 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002320 unsigned NumInits) {
2321 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002322 return;
Mike Stump11289f42009-09-09 15:08:12 +00002323
Argyrios Kyrtzidis1cb0de12010-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) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002328 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-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 Carlssone0eebb32009-08-27 05:45:01 +00002337 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002338
John McCallbb7b6582010-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 Stump11289f42009-09-09 15:08:12 +00002343
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002344 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2345
John McCallbb7b6582010-04-10 07:37:23 +00002346 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002347 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002348 ClassDecl->vbases_begin(),
2349 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002350 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002351
John McCallbb7b6582010-04-10 07:37:23 +00002352 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002353 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002354 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002355 if (Base->isVirtual())
2356 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002357 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002358 }
Mike Stump11289f42009-09-09 15:08:12 +00002359
John McCallbb7b6582010-04-10 07:37:23 +00002360 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002361 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2362 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002363 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002364
John McCallbb7b6582010-04-10 07:37:23 +00002365 unsigned NumIdealInits = IdealInitKeys.size();
2366 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002367
Alexis Hunt1d792652011-01-08 20:30:50 +00002368 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002369 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002370 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002371 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00002377 break;
John McCallbb7b6582010-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 Gregoraabdfcb2010-05-20 23:49:34 +00002382 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002383 Sema::SemaDiagnosticBuilder D =
2384 SemaRef.Diag(PrevInit->getSourceLocation(),
2385 diag::warn_initializer_out_of_order);
2386
Francois Pichetd583da02010-12-04 09:14:42 +00002387 if (PrevInit->isAnyMemberInitializer())
2388 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002389 else
2390 D << 1 << PrevInit->getBaseClassInfo()->getType();
2391
Francois Pichetd583da02010-12-04 09:14:42 +00002392 if (Init->isAnyMemberInitializer())
2393 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00002400 break;
John McCallbb7b6582010-04-10 07:37:23 +00002401
2402 assert(IdealIndex != NumIdealInits &&
2403 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002404 }
John McCallbb7b6582010-04-10 07:37:23 +00002405
2406 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002407 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002408}
2409
John McCall23eebd92010-04-10 09:28:51 +00002410namespace {
2411bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002412 CXXCtorInitializer *Init,
2413 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-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 McCall424cec92011-01-19 06:33:43 +00002425 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00002438typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002439typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2440
2441bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002442 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002443 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002444 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-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 Carlssone857b292010-04-02 03:37:03 +00002475/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002476void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-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 McCall48871652010-08-21 09:40:31 +00002486 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002487
2488 if (!Constructor) {
2489 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2490 return;
2491 }
2492
Alexis Hunt1d792652011-01-08 20:30:50 +00002493 CXXCtorInitializer **MemInits =
2494 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-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*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002499 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002500
2501 // Mapping for the inconsistent anonymous-union initializers check.
2502 RedundantUnionMap MemberUnions;
2503
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002504 bool HadError = false;
2505 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002506 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002507
Abramo Bagnara341d7832010-05-26 18:09:23 +00002508 // Set the source order index.
2509 Init->setSourceOrder(i);
2510
Francois Pichetd583da02010-12-04 09:14:42 +00002511 if (Init->isAnyMemberInitializer()) {
2512 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002513 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2514 CheckRedundantUnionInit(*this, Init, MemberUnions))
2515 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002516 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002517 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2518 if (CheckRedundantInit(*this, Init, Members[Key]))
2519 HadError = true;
Alexis Huntc5575cc2011-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;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002528 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002529 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002530 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002531 // Return immediately as the initializer is set.
2532 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002533 }
Anders Carlssone857b292010-04-02 03:37:03 +00002534 }
2535
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002536 if (HadError)
2537 return;
2538
Anders Carlssone857b292010-04-02 03:37:03 +00002539 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002540
Alexis Hunt1d792652011-01-08 20:30:50 +00002541 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002542}
2543
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002544void
John McCalla6309952010-03-16 21:39:52 +00002545Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2546 CXXRecordDecl *ClassDecl) {
2547 // Ignore dependent contexts.
2548 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002549 return;
John McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002555
Anders Carlssondee9a302009-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 Jahanian16f94c62010-05-17 18:15:18 +00002560 if (Field->isInvalidDecl())
2561 continue;
Anders Carlssondee9a302009-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-Gay93615d92011-03-28 01:39:13 +00002569 if (FieldClassDecl->isInvalidDecl())
2570 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002571 if (FieldClassDecl->hasTrivialDestructor())
2572 continue;
2573
Douglas Gregore71edda2010-07-01 22:47:18 +00002574 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002575 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002576 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002577 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002578 << Field->getDeclName()
2579 << FieldType);
2580
John McCalla6309952010-03-16 21:39:52 +00002581 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002582 }
2583
John McCall1064d7e2010-03-16 05:22:47 +00002584 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2585
Anders Carlssondee9a302009-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 McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002593 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002594 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002595
John McCall1064d7e2010-03-16 05:22:47 +00002596 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-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 Carlssondee9a302009-11-17 04:44:12 +00002601 if (BaseClassDecl->hasTrivialDestructor())
2602 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002603
Douglas Gregore71edda2010-07-01 22:47:18 +00002604 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002605 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-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 Gregor89336232010-03-29 23:34:08 +00002609 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002610 << Base->getType()
2611 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002612
John McCalla6309952010-03-16 21:39:52 +00002613 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002614 }
2615
2616 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002617 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2618 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-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 McCall1064d7e2010-03-16 05:22:47 +00002627 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-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 Jahanian37d06562009-09-03 23:18:17 +00002632 if (BaseClassDecl->hasTrivialDestructor())
2633 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002634
Douglas Gregore71edda2010-07-01 22:47:18 +00002635 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002636 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002637 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002638 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002639 << VBase->getType());
2640
John McCalla6309952010-03-16 21:39:52 +00002641 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002642 }
2643}
2644
John McCall48871652010-08-21 09:40:31 +00002645void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002646 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002647 return;
Mike Stump11289f42009-09-09 15:08:12 +00002648
Mike Stump11289f42009-09-09 15:08:12 +00002649 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002650 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002651 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002652}
2653
Mike Stump11289f42009-09-09 15:08:12 +00002654bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002655 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002656 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002657 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002658 else
John McCall02db245d2010-08-18 09:41:07 +00002659 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002660}
2661
Anders Carlssoneabf7702009-08-27 00:13:57 +00002662bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002663 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002664 if (!getLangOptions().CPlusPlus)
2665 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002666
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002667 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002668 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002669
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002670 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002671 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002672 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002673 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002674
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002675 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002676 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002677 }
Mike Stump11289f42009-09-09 15:08:12 +00002678
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002679 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002680 if (!RT)
2681 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002682
John McCall67da35c2010-02-04 22:26:26 +00002683 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002684
John McCall02db245d2010-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 McCall67da35c2010-02-04 22:26:26 +00002690 return false;
2691
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002692 if (!RD->isAbstract())
2693 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002694
Anders Carlssoneabf7702009-08-27 00:13:57 +00002695 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002696 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002697
John McCall02db245d2010-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 Carlsson576cc6f2009-03-22 20:18:17 +00002704 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002705 return;
Mike Stump11289f42009-09-09 15:08:12 +00002706
Douglas Gregor4165bd62010-03-23 23:47:56 +00002707 CXXFinalOverriderMap FinalOverriders;
2708 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002709
Anders Carlssona2f74f32010-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 Gregor4165bd62010-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 Stump11289f42009-09-09 15:08:12 +00002725
Douglas Gregor4165bd62010-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 Carlssona2f74f32010-06-03 01:00:02 +00002733 if (!SeenPureMethods.insert(SO->second.front().Method))
2734 continue;
2735
Douglas Gregor4165bd62010-03-23 23:47:56 +00002736 Diag(SO->second.front().Method->getLocation(),
2737 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002738 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002739 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002740 }
2741
2742 if (!PureVirtualClassDiagSet)
2743 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2744 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002745}
2746
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002747namespace {
John McCall02db245d2010-08-18 09:41:07 +00002748struct AbstractUsageInfo {
2749 Sema &S;
2750 CXXRecordDecl *Record;
2751 CanQualType AbstractType;
2752 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002753
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002759
John McCall02db245d2010-08-18 09:41:07 +00002760 void DiagnoseAbstractType() {
2761 if (Invalid) return;
2762 S.DiagnoseAbstractType(Record);
2763 Invalid = true;
2764 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002765
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002782 }
John McCall02db245d2010-08-18 09:41:07 +00002783 }
Mike Stump11289f42009-09-09 15:08:12 +00002784
John McCall02db245d2010-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 Gregor385d3fd2011-02-22 23:21:06 +00002788 if (!TL.getArg(I))
2789 continue;
2790
John McCall02db245d2010-08-18 09:41:07 +00002791 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2792 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002793 }
John McCall02db245d2010-08-18 09:41:07 +00002794 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002795
John McCall02db245d2010-08-18 09:41:07 +00002796 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2797 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002808 }
John McCall02db245d2010-08-18 09:41:07 +00002809 }
Mike Stump11289f42009-09-09 15:08:12 +00002810
John McCall02db245d2010-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 Stump11289f42009-09-09 15:08:12 +00002820
John McCall02db245d2010-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 Carlssonb57738b2009-03-24 17:23:42 +00002839 }
John McCall02db245d2010-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.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002867 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002910}
2911
Douglas Gregorc99f1552009-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 Gregor0be31a22010-07-02 17:43:08 +00002915void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002916 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002917 return;
2918
John McCall02db245d2010-08-18 09:41:07 +00002919 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2920 AbstractUsageInfo Info(*this, Record);
2921 CheckAbstractClassUsage(Info, Record);
2922 }
Douglas Gregor454a5b62010-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 Kramer659d7fc2010-04-16 17:43:15 +00002934 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-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 Gregor88d292c2010-05-13 16:44:06 +00002947
Anders Carlssone771e762011-01-25 18:08:22 +00002948 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002949 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-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 Pichet783dd6e2010-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 Gregor36c22a22010-10-15 13:21:21 +00002967 break;
2968 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002969 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002970 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002971
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002972 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002973 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002974 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002975 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002976 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2977 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2978 }
Argyrios Kyrtzidis7272d9c2011-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 Kyrtzidis7a1778e2011-03-03 22:58:57 +00002986 if (!(*M)->isStatic())
2987 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002988 }
2989 }
Sebastian Redl08905022011-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 Redlc1f8e492011-03-12 13:44:32 +00002998 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002999
3000 CheckExplicitlyDefaultedMethods(Record);
3001}
3002
3003void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003004 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3005 ME = Record->method_end();
3006 MI != ME; ++MI) {
3007 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3008 switch (getSpecialMember(*MI)) {
3009 case CXXDefaultConstructor:
3010 CheckExplicitlyDefaultedDefaultConstructor(
3011 cast<CXXConstructorDecl>(*MI));
3012 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003013
Alexis Huntf91729462011-05-12 22:46:25 +00003014 case CXXDestructor:
3015 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3016 break;
3017
3018 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003019 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3020 break;
3021
Alexis Huntf91729462011-05-12 22:46:25 +00003022 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003023 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003024 break;
3025
3026 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00003027 // FIXME: Do moves once they exist
Alexis Huntf91729462011-05-12 22:46:25 +00003028 llvm_unreachable("non-special member explicitly defaulted!");
3029 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003030 }
3031 }
3032
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003033}
3034
3035void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3036 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3037
3038 // Whether this was the first-declared instance of the constructor.
3039 // This affects whether we implicitly add an exception spec (and, eventually,
3040 // constexpr). It is also ill-formed to explicitly default a constructor such
3041 // that it would be deleted. (C++0x [decl.fct.def.default])
3042 bool First = CD == CD->getCanonicalDecl();
3043
Alexis Hunt913820d2011-05-13 06:10:58 +00003044 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003045 if (CD->getNumParams() != 0) {
3046 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3047 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003048 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003049 }
3050
3051 ImplicitExceptionSpecification Spec
3052 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3053 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3054 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3055 *ExceptionType = Context.getFunctionType(
3056 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3057
3058 if (CtorType->hasExceptionSpec()) {
3059 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003060 PDiag(diag::err_incorrect_defaulted_exception_spec)
3061 << 0 /* default constructor */,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003062 PDiag(),
3063 ExceptionType, SourceLocation(),
3064 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003065 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003066 }
3067 } else if (First) {
3068 // We set the declaration to have the computed exception spec here.
3069 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003070 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003071 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3072 }
Alexis Huntb3153022011-05-12 03:51:48 +00003073
Alexis Hunt913820d2011-05-13 06:10:58 +00003074 if (HadError) {
3075 CD->setInvalidDecl();
3076 return;
3077 }
3078
Alexis Huntb3153022011-05-12 03:51:48 +00003079 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003080 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003081 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003082 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003083 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Huntf91729462011-05-12 22:46:25 +00003084 << 0 /* default constructor */;
Alexis Hunt913820d2011-05-13 06:10:58 +00003085 CD->setInvalidDecl();
3086 }
3087 }
3088}
3089
3090void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3091 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3092
3093 // Whether this was the first-declared instance of the constructor.
3094 bool First = CD == CD->getCanonicalDecl();
3095
3096 bool HadError = false;
3097 if (CD->getNumParams() != 1) {
3098 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3099 << CD->getSourceRange();
3100 HadError = true;
3101 }
3102
3103 ImplicitExceptionSpecification Spec(Context);
3104 bool Const;
3105 llvm::tie(Spec, Const) =
3106 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3107
3108 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3109 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3110 *ExceptionType = Context.getFunctionType(
3111 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3112
3113 // Check for parameter type matching.
3114 // This is a copy ctor so we know it's a cv-qualified reference to T.
3115 QualType ArgType = CtorType->getArgType(0);
3116 if (ArgType->getPointeeType().isVolatileQualified()) {
3117 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3118 HadError = true;
3119 }
3120 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3121 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3122 HadError = true;
3123 }
3124
3125 if (CtorType->hasExceptionSpec()) {
3126 if (CheckEquivalentExceptionSpec(
3127 PDiag(diag::err_incorrect_defaulted_exception_spec)
3128 << 1 /* copy constructor */,
3129 PDiag(),
3130 ExceptionType, SourceLocation(),
3131 CtorType, CD->getLocation())) {
3132 HadError = true;
3133 }
3134 } else if (First) {
3135 // We set the declaration to have the computed exception spec here.
3136 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003137 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003138 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3139 }
3140
3141 if (HadError) {
3142 CD->setInvalidDecl();
3143 return;
3144 }
3145
3146 if (ShouldDeleteCopyConstructor(CD)) {
3147 if (First) {
3148 CD->setDeletedAsWritten();
3149 } else {
3150 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3151 << 1 /* copy constructor */;
3152 CD->setInvalidDecl();
3153 }
Alexis Huntb3153022011-05-12 03:51:48 +00003154 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003155}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003156
Alexis Huntc9a55732011-05-14 05:23:28 +00003157void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3158 assert(MD->isExplicitlyDefaulted());
3159
3160 // Whether this was the first-declared instance of the operator
3161 bool First = MD == MD->getCanonicalDecl();
3162
3163 bool HadError = false;
3164 if (MD->getNumParams() != 1) {
3165 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3166 << MD->getSourceRange();
3167 HadError = true;
3168 }
3169
3170 QualType ReturnType =
3171 MD->getType()->getAs<FunctionType>()->getResultType();
3172 if (!ReturnType->isLValueReferenceType() ||
3173 !Context.hasSameType(
3174 Context.getCanonicalType(ReturnType->getPointeeType()),
3175 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3176 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3177 HadError = true;
3178 }
3179
3180 ImplicitExceptionSpecification Spec(Context);
3181 bool Const;
3182 llvm::tie(Spec, Const) =
3183 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3184
3185 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3186 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3187 *ExceptionType = Context.getFunctionType(
3188 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3189
Alexis Huntc9a55732011-05-14 05:23:28 +00003190 QualType ArgType = OperType->getArgType(0);
Alexis Hunt604aeb32011-05-17 20:44:43 +00003191 if (!ArgType->isReferenceType()) {
3192 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003193 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003194 } else {
3195 if (ArgType->getPointeeType().isVolatileQualified()) {
3196 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3197 HadError = true;
3198 }
3199 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3200 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3201 HadError = true;
3202 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003203 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003204
Alexis Huntc9a55732011-05-14 05:23:28 +00003205 if (OperType->getTypeQuals()) {
3206 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3207 HadError = true;
3208 }
3209
3210 if (OperType->hasExceptionSpec()) {
3211 if (CheckEquivalentExceptionSpec(
3212 PDiag(diag::err_incorrect_defaulted_exception_spec)
3213 << 2 /* copy assignment operator */,
3214 PDiag(),
3215 ExceptionType, SourceLocation(),
3216 OperType, MD->getLocation())) {
3217 HadError = true;
3218 }
3219 } else if (First) {
3220 // We set the declaration to have the computed exception spec here.
3221 // We duplicate the one parameter type.
3222 EPI.RefQualifier = OperType->getRefQualifier();
3223 EPI.ExtInfo = OperType->getExtInfo();
3224 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3225 }
3226
3227 if (HadError) {
3228 MD->setInvalidDecl();
3229 return;
3230 }
3231
3232 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3233 if (First) {
3234 MD->setDeletedAsWritten();
3235 } else {
3236 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3237 << 2 /* copy assignment operator */;
3238 MD->setInvalidDecl();
3239 }
3240 }
3241}
3242
Alexis Huntf91729462011-05-12 22:46:25 +00003243void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3244 assert(DD->isExplicitlyDefaulted());
3245
3246 // Whether this was the first-declared instance of the destructor.
3247 bool First = DD == DD->getCanonicalDecl();
3248
3249 ImplicitExceptionSpecification Spec
3250 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3251 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3252 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3253 *ExceptionType = Context.getFunctionType(
3254 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3255
3256 if (DtorType->hasExceptionSpec()) {
3257 if (CheckEquivalentExceptionSpec(
3258 PDiag(diag::err_incorrect_defaulted_exception_spec)
3259 << 3 /* destructor */,
3260 PDiag(),
3261 ExceptionType, SourceLocation(),
3262 DtorType, DD->getLocation())) {
3263 DD->setInvalidDecl();
3264 return;
3265 }
3266 } else if (First) {
3267 // We set the declaration to have the computed exception spec here.
3268 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003269 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003270 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3271 }
3272
3273 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003274 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003275 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003276 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003277 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3278 << 3 /* destructor */;
Alexis Hunt913820d2011-05-13 06:10:58 +00003279 DD->setInvalidDecl();
3280 }
Alexis Huntf91729462011-05-12 22:46:25 +00003281 }
Alexis Huntf91729462011-05-12 22:46:25 +00003282}
3283
Alexis Huntea6f0322011-05-11 22:34:38 +00003284bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3285 CXXRecordDecl *RD = CD->getParent();
3286 assert(!RD->isDependentType() && "do deletion after instantiation");
3287 if (!LangOpts.CPlusPlus0x)
3288 return false;
3289
Alexis Hunte77a28f2011-05-18 03:41:58 +00003290 SourceLocation Loc = CD->getLocation();
3291
Alexis Huntea6f0322011-05-11 22:34:38 +00003292 // Do access control from the constructor
3293 ContextRAII CtorContext(*this, CD);
3294
3295 bool Union = RD->isUnion();
3296 bool AllConst = true;
3297
Alexis Huntea6f0322011-05-11 22:34:38 +00003298 // We do this because we should never actually use an anonymous
3299 // union's constructor.
3300 if (Union && RD->isAnonymousStructOrUnion())
3301 return false;
3302
3303 // FIXME: We should put some diagnostic logic right into this function.
3304
3305 // C++0x [class.ctor]/5
3306 // A defaulted default constructor for class X is defined as delete if:
3307
3308 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3309 BE = RD->bases_end();
3310 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003311 // We'll handle this one later
3312 if (BI->isVirtual())
3313 continue;
3314
Alexis Huntea6f0322011-05-11 22:34:38 +00003315 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3316 assert(BaseDecl && "base isn't a CXXRecordDecl");
3317
3318 // -- any [direct base class] has a type with a destructor that is
3319 // delete or inaccessible from the defaulted default constructor
3320 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3321 if (BaseDtor->isDeleted())
3322 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003323 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003324 AR_accessible)
3325 return true;
3326
Alexis Huntea6f0322011-05-11 22:34:38 +00003327 // -- any [direct base class either] has no default constructor or
3328 // overload resolution as applied to [its] default constructor
3329 // results in an ambiguity or in a function that is deleted or
3330 // inaccessible from the defaulted default constructor
3331 InitializedEntity BaseEntity =
3332 InitializedEntity::InitializeBase(Context, BI, 0);
3333 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003334 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Huntea6f0322011-05-11 22:34:38 +00003335
3336 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3337
3338 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3339 return true;
3340 }
3341
3342 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3343 BE = RD->vbases_end();
3344 BI != BE; ++BI) {
3345 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3346 assert(BaseDecl && "base isn't a CXXRecordDecl");
3347
3348 // -- any [virtual base class] has a type with a destructor that is
3349 // delete or inaccessible from the defaulted default constructor
3350 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3351 if (BaseDtor->isDeleted())
3352 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003353 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003354 AR_accessible)
3355 return true;
3356
3357 // -- any [virtual base class either] has no default constructor or
3358 // overload resolution as applied to [its] default constructor
3359 // results in an ambiguity or in a function that is deleted or
3360 // inaccessible from the defaulted default constructor
3361 InitializedEntity BaseEntity =
3362 InitializedEntity::InitializeBase(Context, BI, BI);
3363 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003364 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Huntea6f0322011-05-11 22:34:38 +00003365
3366 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3367
3368 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3369 return true;
3370 }
3371
3372 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3373 FE = RD->field_end();
3374 FI != FE; ++FI) {
3375 QualType FieldType = Context.getBaseElementType(FI->getType());
3376 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3377
3378 // -- any non-static data member with no brace-or-equal-initializer is of
3379 // reference type
3380 if (FieldType->isReferenceType())
3381 return true;
3382
3383 // -- X is a union and all its variant members are of const-qualified type
3384 // (or array thereof)
3385 if (Union && !FieldType.isConstQualified())
3386 AllConst = false;
3387
3388 if (FieldRecord) {
3389 // -- X is a union-like class that has a variant member with a non-trivial
3390 // default constructor
3391 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3392 return true;
3393
3394 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3395 if (FieldDtor->isDeleted())
3396 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003397 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003398 AR_accessible)
3399 return true;
3400
3401 // -- any non-variant non-static data member of const-qualified type (or
3402 // array thereof) with no brace-or-equal-initializer does not have a
3403 // user-provided default constructor
3404 if (FieldType.isConstQualified() &&
3405 !FieldRecord->hasUserProvidedDefaultConstructor())
3406 return true;
3407
3408 if (!Union && FieldRecord->isUnion() &&
3409 FieldRecord->isAnonymousStructOrUnion()) {
3410 // We're okay to reuse AllConst here since we only care about the
3411 // value otherwise if we're in a union.
3412 AllConst = true;
3413
3414 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3415 UE = FieldRecord->field_end();
3416 UI != UE; ++UI) {
3417 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3418 CXXRecordDecl *UnionFieldRecord =
3419 UnionFieldType->getAsCXXRecordDecl();
3420
3421 if (!UnionFieldType.isConstQualified())
3422 AllConst = false;
3423
3424 if (UnionFieldRecord &&
3425 !UnionFieldRecord->hasTrivialDefaultConstructor())
3426 return true;
3427 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003428
Alexis Huntea6f0322011-05-11 22:34:38 +00003429 if (AllConst)
3430 return true;
3431
3432 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003433 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003434 continue;
3435 }
Alexis Hunta671bca2011-05-20 21:43:47 +00003436 } else if (!Union && FieldType.isConstQualified()) {
3437 // -- any non-variant non-static data member of const-qualified type (or
3438 // array thereof) with no brace-or-equal-initializer does not have a
3439 // user-provided default constructor
3440 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003441 }
3442
3443 InitializedEntity MemberEntity =
3444 InitializedEntity::InitializeMember(*FI, 0);
3445 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003446 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Huntea6f0322011-05-11 22:34:38 +00003447
3448 InitializationSequence InitSeq(*this, MemberEntity, Kind, 0, 0);
3449
3450 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3451 return true;
3452 }
3453
3454 if (Union && AllConst)
3455 return true;
3456
3457 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003458}
3459
Alexis Hunt913820d2011-05-13 06:10:58 +00003460bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003461 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003462 assert(!RD->isDependentType() && "do deletion after instantiation");
3463 if (!LangOpts.CPlusPlus0x)
3464 return false;
3465
Alexis Hunte77a28f2011-05-18 03:41:58 +00003466 SourceLocation Loc = CD->getLocation();
3467
Alexis Hunt913820d2011-05-13 06:10:58 +00003468 // Do access control from the constructor
3469 ContextRAII CtorContext(*this, CD);
3470
Alexis Huntc9a55732011-05-14 05:23:28 +00003471 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003472
Alexis Huntc9a55732011-05-14 05:23:28 +00003473 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3474 "copy assignment arg has no pointee type");
3475 bool ConstArg =
3476 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Alexis Hunt913820d2011-05-13 06:10:58 +00003477
3478 // We do this because we should never actually use an anonymous
3479 // union's constructor.
3480 if (Union && RD->isAnonymousStructOrUnion())
3481 return false;
3482
3483 // FIXME: We should put some diagnostic logic right into this function.
3484
3485 // C++0x [class.copy]/11
3486 // A defaulted [copy] constructor for class X is defined as delete if X has:
3487
3488 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3489 BE = RD->bases_end();
3490 BI != BE; ++BI) {
3491 // We'll handle this one later
3492 if (BI->isVirtual())
3493 continue;
3494
3495 QualType BaseType = BI->getType();
3496 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3497 assert(BaseDecl && "base isn't a CXXRecordDecl");
3498
3499 // -- any [direct base class] of a type with a destructor that is deleted or
3500 // inaccessible from the defaulted constructor
3501 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3502 if (BaseDtor->isDeleted())
3503 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003504 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003505 AR_accessible)
3506 return true;
3507
3508 // -- a [direct base class] B that cannot be [copied] because overload
3509 // resolution, as applied to B's [copy] constructor, results in an
3510 // ambiguity or a function that is deleted or inaccessible from the
3511 // defaulted constructor
3512 InitializedEntity BaseEntity =
3513 InitializedEntity::InitializeBase(Context, BI, 0);
3514 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003515 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Hunt913820d2011-05-13 06:10:58 +00003516
3517 // Construct a fake expression to perform the copy overloading.
3518 QualType ArgType = BaseType.getUnqualifiedType();
Alexis Hunt913820d2011-05-13 06:10:58 +00003519 if (ConstArg)
3520 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003521 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Alexis Hunt913820d2011-05-13 06:10:58 +00003522
3523 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1);
3524
3525 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3526 return true;
3527 }
3528
3529 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3530 BE = RD->vbases_end();
3531 BI != BE; ++BI) {
3532 QualType BaseType = BI->getType();
3533 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3534 assert(BaseDecl && "base isn't a CXXRecordDecl");
3535
3536 // -- any [direct base class] of a type with a destructor that is deleted or
3537 // inaccessible from the defaulted constructor
3538 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3539 if (BaseDtor->isDeleted())
3540 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003541 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003542 AR_accessible)
3543 return true;
3544
3545 // -- a [virtual base class] B that cannot be [copied] because overload
3546 // resolution, as applied to B's [copy] constructor, results in an
3547 // ambiguity or a function that is deleted or inaccessible from the
3548 // defaulted constructor
3549 InitializedEntity BaseEntity =
3550 InitializedEntity::InitializeBase(Context, BI, BI);
3551 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003552 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Hunt913820d2011-05-13 06:10:58 +00003553
3554 // Construct a fake expression to perform the copy overloading.
3555 QualType ArgType = BaseType.getUnqualifiedType();
Alexis Hunt913820d2011-05-13 06:10:58 +00003556 if (ConstArg)
3557 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003558 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Alexis Hunt913820d2011-05-13 06:10:58 +00003559
3560 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1);
3561
3562 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3563 return true;
3564 }
3565
3566 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3567 FE = RD->field_end();
3568 FI != FE; ++FI) {
3569 QualType FieldType = Context.getBaseElementType(FI->getType());
3570
3571 // -- for a copy constructor, a non-static data member of rvalue reference
3572 // type
3573 if (FieldType->isRValueReferenceType())
3574 return true;
3575
3576 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3577
3578 if (FieldRecord) {
3579 // This is an anonymous union
3580 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3581 // Anonymous unions inside unions do not variant members create
3582 if (!Union) {
3583 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3584 UE = FieldRecord->field_end();
3585 UI != UE; ++UI) {
3586 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3587 CXXRecordDecl *UnionFieldRecord =
3588 UnionFieldType->getAsCXXRecordDecl();
3589
3590 // -- a variant member with a non-trivial [copy] constructor and X
3591 // is a union-like class
3592 if (UnionFieldRecord &&
3593 !UnionFieldRecord->hasTrivialCopyConstructor())
3594 return true;
3595 }
3596 }
3597
3598 // Don't try to initalize an anonymous union
3599 continue;
3600 } else {
3601 // -- a variant member with a non-trivial [copy] constructor and X is a
3602 // union-like class
3603 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3604 return true;
3605
3606 // -- any [non-static data member] of a type with a destructor that is
3607 // deleted or inaccessible from the defaulted constructor
3608 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3609 if (FieldDtor->isDeleted())
3610 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003611 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003612 AR_accessible)
3613 return true;
3614 }
3615 }
3616
Alexis Huntb5b14c82011-05-13 21:10:11 +00003617 llvm::SmallVector<InitializedEntity, 4> Entities;
3618 QualType CurType = FI->getType();
3619 Entities.push_back(InitializedEntity::InitializeMember(*FI, 0));
3620 while (CurType->isArrayType()) {
3621 Entities.push_back(InitializedEntity::InitializeElement(Context, 0,
3622 Entities.back()));
3623 CurType = Context.getAsArrayType(CurType)->getElementType();
3624 }
3625
Alexis Hunt913820d2011-05-13 06:10:58 +00003626 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003627 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Hunt913820d2011-05-13 06:10:58 +00003628
3629 // Construct a fake expression to perform the copy overloading.
3630 QualType ArgType = FieldType;
3631 if (ArgType->isReferenceType())
3632 ArgType = ArgType->getPointeeType();
Alexis Huntc9a55732011-05-14 05:23:28 +00003633 else if (ConstArg)
Alexis Hunt913820d2011-05-13 06:10:58 +00003634 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003635 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Alexis Hunt913820d2011-05-13 06:10:58 +00003636
Alexis Huntb5b14c82011-05-13 21:10:11 +00003637 InitializationSequence InitSeq(*this, Entities.back(), Kind, &Arg, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00003638
3639 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3640 return true;
3641 }
3642
3643 return false;
3644}
3645
Alexis Huntb2f27802011-05-14 05:23:24 +00003646bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3647 CXXRecordDecl *RD = MD->getParent();
3648 assert(!RD->isDependentType() && "do deletion after instantiation");
3649 if (!LangOpts.CPlusPlus0x)
3650 return false;
3651
Alexis Hunte77a28f2011-05-18 03:41:58 +00003652 SourceLocation Loc = MD->getLocation();
3653
Alexis Huntb2f27802011-05-14 05:23:24 +00003654 // Do access control from the constructor
3655 ContextRAII MethodContext(*this, MD);
3656
3657 bool Union = RD->isUnion();
3658
Alexis Huntc9a55732011-05-14 05:23:28 +00003659 bool ConstArg =
3660 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Alexis Huntb2f27802011-05-14 05:23:24 +00003661
3662 // We do this because we should never actually use an anonymous
3663 // union's constructor.
3664 if (Union && RD->isAnonymousStructOrUnion())
3665 return false;
3666
3667 DeclarationName OperatorName =
3668 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunte77a28f2011-05-18 03:41:58 +00003669 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
Alexis Huntb2f27802011-05-14 05:23:24 +00003670 R.suppressDiagnostics();
3671
3672 // FIXME: We should put some diagnostic logic right into this function.
3673
3674 // C++0x [class.copy]/11
3675 // A defaulted [copy] assignment operator for class X is defined as deleted
3676 // if X has:
3677
3678 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3679 BE = RD->bases_end();
3680 BI != BE; ++BI) {
3681 // We'll handle this one later
3682 if (BI->isVirtual())
3683 continue;
3684
3685 QualType BaseType = BI->getType();
3686 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3687 assert(BaseDecl && "base isn't a CXXRecordDecl");
3688
3689 // -- a [direct base class] B that cannot be [copied] because overload
3690 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00003691 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00003692 // assignment operator
3693
3694 LookupQualifiedName(R, BaseDecl, false);
3695
3696 // Filter out any result that isn't a copy-assignment operator.
3697 LookupResult::Filter F = R.makeFilter();
3698 while (F.hasNext()) {
3699 NamedDecl *D = F.next();
3700 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3701 if (Method->isCopyAssignmentOperator())
3702 continue;
3703
3704 F.erase();
3705 }
3706 F.done();
3707
3708 // Build a fake argument expression
3709 QualType ArgType = BaseType;
Alexis Huntc9a55732011-05-14 05:23:28 +00003710 QualType ThisType = BaseType;
Alexis Huntb2f27802011-05-14 05:23:24 +00003711 if (ConstArg)
3712 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003713 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3714 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Alexis Huntc9a55732011-05-14 05:23:28 +00003715 };
Alexis Huntb2f27802011-05-14 05:23:24 +00003716
Alexis Hunte77a28f2011-05-18 03:41:58 +00003717 OverloadCandidateSet OCS((Loc));
Alexis Huntb2f27802011-05-14 05:23:24 +00003718 OverloadCandidateSet::iterator Best;
3719
Alexis Huntc9a55732011-05-14 05:23:28 +00003720 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
Alexis Huntb2f27802011-05-14 05:23:24 +00003721
Alexis Hunte77a28f2011-05-18 03:41:58 +00003722 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Alexis Huntb2f27802011-05-14 05:23:24 +00003723 OR_Success)
3724 return true;
3725 }
3726
3727 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3728 BE = RD->vbases_end();
3729 BI != BE; ++BI) {
3730 QualType BaseType = BI->getType();
3731 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3732 assert(BaseDecl && "base isn't a CXXRecordDecl");
3733
Alexis Huntb2f27802011-05-14 05:23:24 +00003734 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00003735 // resolution, as applied to B's [copy] assignment operator, results in
3736 // an ambiguity or a function that is deleted or inaccessible from the
3737 // assignment operator
Alexis Huntb2f27802011-05-14 05:23:24 +00003738
Alexis Huntc9a55732011-05-14 05:23:28 +00003739 LookupQualifiedName(R, BaseDecl, false);
3740
3741 // Filter out any result that isn't a copy-assignment operator.
3742 LookupResult::Filter F = R.makeFilter();
3743 while (F.hasNext()) {
3744 NamedDecl *D = F.next();
3745 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3746 if (Method->isCopyAssignmentOperator())
3747 continue;
3748
3749 F.erase();
3750 }
3751 F.done();
3752
3753 // Build a fake argument expression
3754 QualType ArgType = BaseType;
3755 QualType ThisType = BaseType;
Alexis Huntb2f27802011-05-14 05:23:24 +00003756 if (ConstArg)
3757 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003758 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3759 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Alexis Huntc9a55732011-05-14 05:23:28 +00003760 };
Alexis Huntb2f27802011-05-14 05:23:24 +00003761
Alexis Hunte77a28f2011-05-18 03:41:58 +00003762 OverloadCandidateSet OCS((Loc));
Alexis Huntc9a55732011-05-14 05:23:28 +00003763 OverloadCandidateSet::iterator Best;
Alexis Huntb2f27802011-05-14 05:23:24 +00003764
Alexis Huntc9a55732011-05-14 05:23:28 +00003765 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3766
Alexis Hunte77a28f2011-05-18 03:41:58 +00003767 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Alexis Huntc9a55732011-05-14 05:23:28 +00003768 OR_Success)
Alexis Huntb2f27802011-05-14 05:23:24 +00003769 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00003770 }
3771
3772 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3773 FE = RD->field_end();
3774 FI != FE; ++FI) {
3775 QualType FieldType = Context.getBaseElementType(FI->getType());
3776
3777 // -- a non-static data member of reference type
3778 if (FieldType->isReferenceType())
3779 return true;
3780
3781 // -- a non-static data member of const non-class type (or array thereof)
3782 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3783 return true;
3784
3785 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3786
3787 if (FieldRecord) {
3788 // This is an anonymous union
3789 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3790 // Anonymous unions inside unions do not variant members create
3791 if (!Union) {
3792 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3793 UE = FieldRecord->field_end();
3794 UI != UE; ++UI) {
3795 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3796 CXXRecordDecl *UnionFieldRecord =
3797 UnionFieldType->getAsCXXRecordDecl();
3798
3799 // -- a variant member with a non-trivial [copy] assignment operator
3800 // and X is a union-like class
3801 if (UnionFieldRecord &&
3802 !UnionFieldRecord->hasTrivialCopyAssignment())
3803 return true;
3804 }
3805 }
3806
3807 // Don't try to initalize an anonymous union
3808 continue;
3809 // -- a variant member with a non-trivial [copy] assignment operator
3810 // and X is a union-like class
3811 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3812 return true;
3813 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003814
Alexis Huntc9a55732011-05-14 05:23:28 +00003815 LookupQualifiedName(R, FieldRecord, false);
Alexis Huntb2f27802011-05-14 05:23:24 +00003816
Alexis Huntc9a55732011-05-14 05:23:28 +00003817 // Filter out any result that isn't a copy-assignment operator.
3818 LookupResult::Filter F = R.makeFilter();
3819 while (F.hasNext()) {
3820 NamedDecl *D = F.next();
3821 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3822 if (Method->isCopyAssignmentOperator())
3823 continue;
3824
3825 F.erase();
3826 }
3827 F.done();
Alexis Huntb2f27802011-05-14 05:23:24 +00003828
Alexis Huntc9a55732011-05-14 05:23:28 +00003829 // Build a fake argument expression
3830 QualType ArgType = FieldType;
3831 QualType ThisType = FieldType;
3832 if (ConstArg)
3833 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003834 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3835 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Alexis Huntc9a55732011-05-14 05:23:28 +00003836 };
Alexis Huntb2f27802011-05-14 05:23:24 +00003837
Alexis Hunte77a28f2011-05-18 03:41:58 +00003838 OverloadCandidateSet OCS((Loc));
Alexis Huntc9a55732011-05-14 05:23:28 +00003839 OverloadCandidateSet::iterator Best;
3840
3841 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3842
Alexis Hunte77a28f2011-05-18 03:41:58 +00003843 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Alexis Huntc9a55732011-05-14 05:23:28 +00003844 OR_Success)
3845 return true;
3846 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003847 }
3848
3849 return false;
3850}
3851
Alexis Huntf91729462011-05-12 22:46:25 +00003852bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3853 CXXRecordDecl *RD = DD->getParent();
3854 assert(!RD->isDependentType() && "do deletion after instantiation");
3855 if (!LangOpts.CPlusPlus0x)
3856 return false;
3857
Alexis Hunte77a28f2011-05-18 03:41:58 +00003858 SourceLocation Loc = DD->getLocation();
3859
Alexis Huntf91729462011-05-12 22:46:25 +00003860 // Do access control from the destructor
3861 ContextRAII CtorContext(*this, DD);
3862
3863 bool Union = RD->isUnion();
3864
Alexis Hunt913820d2011-05-13 06:10:58 +00003865 // We do this because we should never actually use an anonymous
3866 // union's destructor.
3867 if (Union && RD->isAnonymousStructOrUnion())
3868 return false;
3869
Alexis Huntf91729462011-05-12 22:46:25 +00003870 // C++0x [class.dtor]p5
3871 // A defaulted destructor for a class X is defined as deleted if:
3872 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3873 BE = RD->bases_end();
3874 BI != BE; ++BI) {
3875 // We'll handle this one later
3876 if (BI->isVirtual())
3877 continue;
3878
3879 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3880 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3881 assert(BaseDtor && "base has no destructor");
3882
3883 // -- any direct or virtual base class has a deleted destructor or
3884 // a destructor that is inaccessible from the defaulted destructor
3885 if (BaseDtor->isDeleted())
3886 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003887 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003888 AR_accessible)
3889 return true;
3890 }
3891
3892 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3893 BE = RD->vbases_end();
3894 BI != BE; ++BI) {
3895 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3896 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3897 assert(BaseDtor && "base has no destructor");
3898
3899 // -- any direct or virtual base class has a deleted destructor or
3900 // a destructor that is inaccessible from the defaulted destructor
3901 if (BaseDtor->isDeleted())
3902 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003903 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003904 AR_accessible)
3905 return true;
3906 }
3907
3908 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3909 FE = RD->field_end();
3910 FI != FE; ++FI) {
3911 QualType FieldType = Context.getBaseElementType(FI->getType());
3912 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3913 if (FieldRecord) {
3914 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3915 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3916 UE = FieldRecord->field_end();
3917 UI != UE; ++UI) {
3918 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3919 CXXRecordDecl *UnionFieldRecord =
3920 UnionFieldType->getAsCXXRecordDecl();
3921
3922 // -- X is a union-like class that has a variant member with a non-
3923 // trivial destructor.
3924 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3925 return true;
3926 }
3927 // Technically we are supposed to do this next check unconditionally.
3928 // But that makes absolutely no sense.
3929 } else {
3930 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3931
3932 // -- any of the non-static data members has class type M (or array
3933 // thereof) and M has a deleted destructor or a destructor that is
3934 // inaccessible from the defaulted destructor
3935 if (FieldDtor->isDeleted())
3936 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003937 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003938 AR_accessible)
3939 return true;
3940
3941 // -- X is a union-like class that has a variant member with a non-
3942 // trivial destructor.
3943 if (Union && !FieldDtor->isTrivial())
3944 return true;
3945 }
3946 }
3947 }
3948
3949 if (DD->isVirtual()) {
3950 FunctionDecl *OperatorDelete = 0;
3951 DeclarationName Name =
3952 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00003953 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00003954 false))
3955 return true;
3956 }
3957
3958
3959 return false;
3960}
3961
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003962/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00003963namespace {
3964 struct FindHiddenVirtualMethodData {
3965 Sema *S;
3966 CXXMethodDecl *Method;
3967 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3968 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3969 };
3970}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003971
3972/// \brief Member lookup function that determines whether a given C++
3973/// method overloads virtual methods in a base class without overriding any,
3974/// to be used with CXXRecordDecl::lookupInBases().
3975static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3976 CXXBasePath &Path,
3977 void *UserData) {
3978 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3979
3980 FindHiddenVirtualMethodData &Data
3981 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3982
3983 DeclarationName Name = Data.Method->getDeclName();
3984 assert(Name.getNameKind() == DeclarationName::Identifier);
3985
3986 bool foundSameNameMethod = false;
3987 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3988 for (Path.Decls = BaseRecord->lookup(Name);
3989 Path.Decls.first != Path.Decls.second;
3990 ++Path.Decls.first) {
3991 NamedDecl *D = *Path.Decls.first;
3992 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003993 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003994 foundSameNameMethod = true;
3995 // Interested only in hidden virtual methods.
3996 if (!MD->isVirtual())
3997 continue;
3998 // If the method we are checking overrides a method from its base
3999 // don't warn about the other overloaded methods.
4000 if (!Data.S->IsOverload(Data.Method, MD, false))
4001 return true;
4002 // Collect the overload only if its hidden.
4003 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4004 overloadedMethods.push_back(MD);
4005 }
4006 }
4007
4008 if (foundSameNameMethod)
4009 Data.OverloadedMethods.append(overloadedMethods.begin(),
4010 overloadedMethods.end());
4011 return foundSameNameMethod;
4012}
4013
4014/// \brief See if a method overloads virtual methods in a base class without
4015/// overriding any.
4016void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4017 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4018 MD->getLocation()) == Diagnostic::Ignored)
4019 return;
4020 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4021 return;
4022
4023 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4024 /*bool RecordPaths=*/false,
4025 /*bool DetectVirtual=*/false);
4026 FindHiddenVirtualMethodData Data;
4027 Data.Method = MD;
4028 Data.S = this;
4029
4030 // Keep the base methods that were overriden or introduced in the subclass
4031 // by 'using' in a set. A base method not in this set is hidden.
4032 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4033 res.first != res.second; ++res.first) {
4034 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4035 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4036 E = MD->end_overridden_methods();
4037 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004038 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004039 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4040 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004041 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004042 }
4043
4044 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4045 !Data.OverloadedMethods.empty()) {
4046 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4047 << MD << (Data.OverloadedMethods.size() > 1);
4048
4049 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4050 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4051 Diag(overloadedMD->getLocation(),
4052 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4053 }
4054 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004055}
4056
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004057void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004058 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004059 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004060 SourceLocation RBrac,
4061 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004062 if (!TagDecl)
4063 return;
Mike Stump11289f42009-09-09 15:08:12 +00004064
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004065 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004066
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004067 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00004068 // strict aliasing violation!
4069 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004070 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004071
Douglas Gregor0be31a22010-07-02 17:43:08 +00004072 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004073 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004074}
4075
Douglas Gregor05379422008-11-03 17:51:48 +00004076/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4077/// special functions, such as the default constructor, copy
4078/// constructor, or destructor, to the given C++ class (C++
4079/// [special]p1). This routine can only be executed just before the
4080/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004081void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004082 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004083 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004084
Douglas Gregor54be3392010-07-01 17:57:27 +00004085 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004086 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004087
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004088 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4089 ++ASTContext::NumImplicitCopyAssignmentOperators;
4090
4091 // If we have a dynamic class, then the copy assignment operator may be
4092 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4093 // it shows up in the right place in the vtable and that we diagnose
4094 // problems with the implicit exception specification.
4095 if (ClassDecl->isDynamicClass())
4096 DeclareImplicitCopyAssignment(ClassDecl);
4097 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004098
Douglas Gregor7454c562010-07-02 20:37:36 +00004099 if (!ClassDecl->hasUserDeclaredDestructor()) {
4100 ++ASTContext::NumImplicitDestructors;
4101
4102 // If we have a dynamic class, then the destructor may be virtual, so we
4103 // have to declare the destructor immediately. This ensures that, e.g., it
4104 // shows up in the right place in the vtable and that we diagnose problems
4105 // with the implicit exception specification.
4106 if (ClassDecl->isDynamicClass())
4107 DeclareImplicitDestructor(ClassDecl);
4108 }
Douglas Gregor05379422008-11-03 17:51:48 +00004109}
4110
Francois Pichet1c229c02011-04-22 22:18:13 +00004111void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4112 if (!D)
4113 return;
4114
4115 int NumParamList = D->getNumTemplateParameterLists();
4116 for (int i = 0; i < NumParamList; i++) {
4117 TemplateParameterList* Params = D->getTemplateParameterList(i);
4118 for (TemplateParameterList::iterator Param = Params->begin(),
4119 ParamEnd = Params->end();
4120 Param != ParamEnd; ++Param) {
4121 NamedDecl *Named = cast<NamedDecl>(*Param);
4122 if (Named->getDeclName()) {
4123 S->AddDecl(Named);
4124 IdResolver.AddDecl(Named);
4125 }
4126 }
4127 }
4128}
4129
John McCall48871652010-08-21 09:40:31 +00004130void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004131 if (!D)
4132 return;
4133
4134 TemplateParameterList *Params = 0;
4135 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4136 Params = Template->getTemplateParameters();
4137 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4138 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4139 Params = PartialSpec->getTemplateParameters();
4140 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004141 return;
4142
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004143 for (TemplateParameterList::iterator Param = Params->begin(),
4144 ParamEnd = Params->end();
4145 Param != ParamEnd; ++Param) {
4146 NamedDecl *Named = cast<NamedDecl>(*Param);
4147 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004148 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004149 IdResolver.AddDecl(Named);
4150 }
4151 }
4152}
4153
John McCall48871652010-08-21 09:40:31 +00004154void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004155 if (!RecordD) return;
4156 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004157 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004158 PushDeclContext(S, Record);
4159}
4160
John McCall48871652010-08-21 09:40:31 +00004161void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004162 if (!RecordD) return;
4163 PopDeclContext();
4164}
4165
Douglas Gregor4d87df52008-12-16 21:30:33 +00004166/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4167/// parsing a top-level (non-nested) C++ class, and we are now
4168/// parsing those parts of the given Method declaration that could
4169/// not be parsed earlier (C++ [class.mem]p2), such as default
4170/// arguments. This action should enter the scope of the given
4171/// Method declaration as if we had just parsed the qualified method
4172/// name. However, it should not bring the parameters into scope;
4173/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004174void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004175}
4176
4177/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4178/// C++ method declaration. We're (re-)introducing the given
4179/// function parameter into scope for use in parsing later parts of
4180/// the method declaration. For example, we could see an
4181/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004182void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004183 if (!ParamD)
4184 return;
Mike Stump11289f42009-09-09 15:08:12 +00004185
John McCall48871652010-08-21 09:40:31 +00004186 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004187
4188 // If this parameter has an unparsed default argument, clear it out
4189 // to make way for the parsed default argument.
4190 if (Param->hasUnparsedDefaultArg())
4191 Param->setDefaultArg(0);
4192
John McCall48871652010-08-21 09:40:31 +00004193 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004194 if (Param->getDeclName())
4195 IdResolver.AddDecl(Param);
4196}
4197
4198/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4199/// processing the delayed method declaration for Method. The method
4200/// declaration is now considered finished. There may be a separate
4201/// ActOnStartOfFunctionDef action later (not necessarily
4202/// immediately!) for this method, if it was also defined inside the
4203/// class body.
John McCall48871652010-08-21 09:40:31 +00004204void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004205 if (!MethodD)
4206 return;
Mike Stump11289f42009-09-09 15:08:12 +00004207
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004208 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004209
John McCall48871652010-08-21 09:40:31 +00004210 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004211
4212 // Now that we have our default arguments, check the constructor
4213 // again. It could produce additional diagnostics or affect whether
4214 // the class has implicitly-declared destructors, among other
4215 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004216 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4217 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004218
4219 // Check the default arguments, which we may have added.
4220 if (!Method->isInvalidDecl())
4221 CheckCXXDefaultArguments(Method);
4222}
4223
Douglas Gregor831c93f2008-11-05 20:51:48 +00004224/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004225/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004226/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004227/// emit diagnostics and set the invalid bit to true. In any case, the type
4228/// will be updated to reflect a well-formed type for the constructor and
4229/// returned.
4230QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004231 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004232 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004233
4234 // C++ [class.ctor]p3:
4235 // A constructor shall not be virtual (10.3) or static (9.4). A
4236 // constructor can be invoked for a const, volatile or const
4237 // volatile object. A constructor shall not be declared const,
4238 // volatile, or const volatile (9.3.2).
4239 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004240 if (!D.isInvalidType())
4241 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4242 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4243 << SourceRange(D.getIdentifierLoc());
4244 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004245 }
John McCall8e7d6562010-08-26 03:08:43 +00004246 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004247 if (!D.isInvalidType())
4248 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4249 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4250 << SourceRange(D.getIdentifierLoc());
4251 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004252 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004253 }
Mike Stump11289f42009-09-09 15:08:12 +00004254
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004255 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004256 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004257 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004258 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4259 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004260 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004261 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4262 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004263 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004264 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4265 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004266 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004267 }
Mike Stump11289f42009-09-09 15:08:12 +00004268
Douglas Gregordb9d6642011-01-26 05:01:58 +00004269 // C++0x [class.ctor]p4:
4270 // A constructor shall not be declared with a ref-qualifier.
4271 if (FTI.hasRefQualifier()) {
4272 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4273 << FTI.RefQualifierIsLValueRef
4274 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4275 D.setInvalidType();
4276 }
4277
Douglas Gregor831c93f2008-11-05 20:51:48 +00004278 // Rebuild the function type "R" without any type qualifiers (in
4279 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004280 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004281 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004282 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4283 return R;
4284
4285 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4286 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004287 EPI.RefQualifier = RQ_None;
4288
Chris Lattner38378bf2009-04-25 08:28:21 +00004289 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004290 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004291}
4292
Douglas Gregor4d87df52008-12-16 21:30:33 +00004293/// CheckConstructor - Checks a fully-formed constructor for
4294/// well-formedness, issuing any diagnostics required. Returns true if
4295/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004296void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004297 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004298 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4299 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004300 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004301
4302 // C++ [class.copy]p3:
4303 // A declaration of a constructor for a class X is ill-formed if
4304 // its first parameter is of type (optionally cv-qualified) X and
4305 // either there are no other parameters or else all other
4306 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004307 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004308 ((Constructor->getNumParams() == 1) ||
4309 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004310 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4311 Constructor->getTemplateSpecializationKind()
4312 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004313 QualType ParamType = Constructor->getParamDecl(0)->getType();
4314 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4315 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004316 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004317 const char *ConstRef
4318 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4319 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004320 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004321 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004322
4323 // FIXME: Rather that making the constructor invalid, we should endeavor
4324 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004325 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004326 }
4327 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004328}
4329
John McCalldeb646e2010-08-04 01:04:25 +00004330/// CheckDestructor - Checks a fully-formed destructor definition for
4331/// well-formedness, issuing any diagnostics required. Returns true
4332/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004333bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004334 CXXRecordDecl *RD = Destructor->getParent();
4335
4336 if (Destructor->isVirtual()) {
4337 SourceLocation Loc;
4338
4339 if (!Destructor->isImplicit())
4340 Loc = Destructor->getLocation();
4341 else
4342 Loc = RD->getLocation();
4343
4344 // If we have a virtual destructor, look up the deallocation function
4345 FunctionDecl *OperatorDelete = 0;
4346 DeclarationName Name =
4347 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004348 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004349 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004350
4351 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004352
4353 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004354 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004355
4356 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004357}
4358
Mike Stump11289f42009-09-09 15:08:12 +00004359static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004360FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4361 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4362 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004363 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004364}
4365
Douglas Gregor831c93f2008-11-05 20:51:48 +00004366/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4367/// the well-formednes of the destructor declarator @p D with type @p
4368/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004369/// emit diagnostics and set the declarator to invalid. Even if this happens,
4370/// will be updated to reflect a well-formed type for the destructor and
4371/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004372QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004373 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004374 // C++ [class.dtor]p1:
4375 // [...] A typedef-name that names a class is a class-name
4376 // (7.1.3); however, a typedef-name that names a class shall not
4377 // be used as the identifier in the declarator for a destructor
4378 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004379 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004380 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004381 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004382 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004383 else if (const TemplateSpecializationType *TST =
4384 DeclaratorType->getAs<TemplateSpecializationType>())
4385 if (TST->isTypeAlias())
4386 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4387 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004388
4389 // C++ [class.dtor]p2:
4390 // A destructor is used to destroy objects of its class type. A
4391 // destructor takes no parameters, and no return type can be
4392 // specified for it (not even void). The address of a destructor
4393 // shall not be taken. A destructor shall not be static. A
4394 // destructor can be invoked for a const, volatile or const
4395 // volatile object. A destructor shall not be declared const,
4396 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004397 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004398 if (!D.isInvalidType())
4399 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4400 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004401 << SourceRange(D.getIdentifierLoc())
4402 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4403
John McCall8e7d6562010-08-26 03:08:43 +00004404 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004405 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004406 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004407 // Destructors don't have return types, but the parser will
4408 // happily parse something like:
4409 //
4410 // class X {
4411 // float ~X();
4412 // };
4413 //
4414 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004415 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4416 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4417 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004418 }
Mike Stump11289f42009-09-09 15:08:12 +00004419
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004420 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004421 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004422 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004423 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4424 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004425 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004426 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4427 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004428 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004429 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4430 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00004431 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004432 }
4433
Douglas Gregordb9d6642011-01-26 05:01:58 +00004434 // C++0x [class.dtor]p2:
4435 // A destructor shall not be declared with a ref-qualifier.
4436 if (FTI.hasRefQualifier()) {
4437 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4438 << FTI.RefQualifierIsLValueRef
4439 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4440 D.setInvalidType();
4441 }
4442
Douglas Gregor831c93f2008-11-05 20:51:48 +00004443 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00004444 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004445 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4446
4447 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00004448 FTI.freeArgs();
4449 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004450 }
4451
Mike Stump11289f42009-09-09 15:08:12 +00004452 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00004453 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004454 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00004455 D.setInvalidType();
4456 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00004457
4458 // Rebuild the function type "R" without any type qualifiers or
4459 // parameters (in case any of the errors above fired) and with
4460 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00004461 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00004462 if (!D.isInvalidType())
4463 return R;
4464
Douglas Gregor95755162010-07-01 05:10:53 +00004465 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004466 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4467 EPI.Variadic = false;
4468 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004469 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004470 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004471}
4472
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004473/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4474/// well-formednes of the conversion function declarator @p D with
4475/// type @p R. If there are any errors in the declarator, this routine
4476/// will emit diagnostics and return true. Otherwise, it will return
4477/// false. Either way, the type @p R will be updated to reflect a
4478/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004479void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00004480 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004481 // C++ [class.conv.fct]p1:
4482 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00004483 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00004484 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00004485 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004486 if (!D.isInvalidType())
4487 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4488 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4489 << SourceRange(D.getIdentifierLoc());
4490 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004491 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004492 }
John McCall212fa2e2010-04-13 00:04:31 +00004493
4494 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4495
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004496 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004497 // Conversion functions don't have return types, but the parser will
4498 // happily parse something like:
4499 //
4500 // class X {
4501 // float operator bool();
4502 // };
4503 //
4504 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00004505 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4506 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4507 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00004508 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004509 }
4510
John McCall212fa2e2010-04-13 00:04:31 +00004511 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4512
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004513 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00004514 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004515 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4516
4517 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004518 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004519 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00004520 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004521 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004522 D.setInvalidType();
4523 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004524
John McCall212fa2e2010-04-13 00:04:31 +00004525 // Diagnose "&operator bool()" and other such nonsense. This
4526 // is actually a gcc extension which we don't support.
4527 if (Proto->getResultType() != ConvType) {
4528 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4529 << Proto->getResultType();
4530 D.setInvalidType();
4531 ConvType = Proto->getResultType();
4532 }
4533
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004534 // C++ [class.conv.fct]p4:
4535 // The conversion-type-id shall not represent a function type nor
4536 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004537 if (ConvType->isArrayType()) {
4538 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4539 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004540 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004541 } else if (ConvType->isFunctionType()) {
4542 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4543 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004544 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004545 }
4546
4547 // Rebuild the function type "R" without any parameters (in case any
4548 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00004549 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00004550 if (D.isInvalidType())
4551 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004552
Douglas Gregor5fb53972009-01-14 15:45:31 +00004553 // C++0x explicit conversion operators.
4554 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00004555 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00004556 diag::warn_explicit_conversion_functions)
4557 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004558}
4559
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004560/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4561/// the declaration of the given C++ conversion function. This routine
4562/// is responsible for recording the conversion function in the C++
4563/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00004564Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004565 assert(Conversion && "Expected to receive a conversion function declaration");
4566
Douglas Gregor4287b372008-12-12 08:25:50 +00004567 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004568
4569 // Make sure we aren't redeclaring the conversion function.
4570 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004571
4572 // C++ [class.conv.fct]p1:
4573 // [...] A conversion function is never used to convert a
4574 // (possibly cv-qualified) object to the (possibly cv-qualified)
4575 // same object type (or a reference to it), to a (possibly
4576 // cv-qualified) base class of that type (or a reference to it),
4577 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00004578 // FIXME: Suppress this warning if the conversion function ends up being a
4579 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00004580 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004581 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004582 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004583 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004584 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4585 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00004586 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004587 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004588 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4589 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004590 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004591 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004592 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004593 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004594 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004595 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004596 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004597 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004598 }
4599
Douglas Gregor457104e2010-09-29 04:25:11 +00004600 if (FunctionTemplateDecl *ConversionTemplate
4601 = Conversion->getDescribedFunctionTemplate())
4602 return ConversionTemplate;
4603
John McCall48871652010-08-21 09:40:31 +00004604 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004605}
4606
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004607//===----------------------------------------------------------------------===//
4608// Namespace Handling
4609//===----------------------------------------------------------------------===//
4610
John McCallb1be5232010-08-26 09:15:37 +00004611
4612
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004613/// ActOnStartNamespaceDef - This is called at the start of a namespace
4614/// definition.
John McCall48871652010-08-21 09:40:31 +00004615Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00004616 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004617 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00004618 SourceLocation IdentLoc,
4619 IdentifierInfo *II,
4620 SourceLocation LBrace,
4621 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004622 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4623 // For anonymous namespace, take the location of the left brace.
4624 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00004625 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004626 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004627 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004628
4629 Scope *DeclRegionScope = NamespcScope->getParent();
4630
Anders Carlssona7bcade2010-02-07 01:09:23 +00004631 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4632
John McCall2faf32c2010-12-10 02:59:44 +00004633 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4634 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00004635
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004636 if (II) {
4637 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00004638 // The identifier in an original-namespace-definition shall not
4639 // have been previously defined in the declarative region in
4640 // which the original-namespace-definition appears. The
4641 // identifier in an original-namespace-definition is the name of
4642 // the namespace. Subsequently in that declarative region, it is
4643 // treated as an original-namespace-name.
4644 //
4645 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00004646 // look through using directives, just look for any ordinary names.
4647
4648 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4649 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4650 Decl::IDNS_Namespace;
4651 NamedDecl *PrevDecl = 0;
4652 for (DeclContext::lookup_result R
4653 = CurContext->getRedeclContext()->lookup(II);
4654 R.first != R.second; ++R.first) {
4655 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4656 PrevDecl = *R.first;
4657 break;
4658 }
4659 }
4660
Douglas Gregor91f84212008-12-11 16:49:14 +00004661 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4662 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004663 if (Namespc->isInline() != OrigNS->isInline()) {
4664 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00004665 if (OrigNS->isInline()) {
4666 // The user probably just forgot the 'inline', so suggest that it
4667 // be added back.
4668 Diag(Namespc->getLocation(),
4669 diag::warn_inline_namespace_reopened_noninline)
4670 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4671 } else {
4672 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4673 << Namespc->isInline();
4674 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004675 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00004676
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004677 // Recover by ignoring the new namespace's inline status.
4678 Namespc->setInline(OrigNS->isInline());
4679 }
4680
Douglas Gregor91f84212008-12-11 16:49:14 +00004681 // Attach this namespace decl to the chain of extended namespace
4682 // definitions.
4683 OrigNS->setNextNamespace(Namespc);
4684 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004685
Mike Stump11289f42009-09-09 15:08:12 +00004686 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00004687 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00004688 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00004689 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004690 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004691 } else if (PrevDecl) {
4692 // This is an invalid name redefinition.
4693 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4694 << Namespc->getDeclName();
4695 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4696 Namespc->setInvalidDecl();
4697 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00004698 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004699 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004700 // This is the first "real" definition of the namespace "std", so update
4701 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004702 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004703 // We had already defined a dummy namespace "std". Link this new
4704 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004705 StdNS->setNextNamespace(Namespc);
4706 StdNS->setLocation(IdentLoc);
4707 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00004708 }
4709
4710 // Make our StdNamespace cache point at the first real definition of the
4711 // "std" namespace.
4712 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00004713 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004714
4715 PushOnScopeChains(Namespc, DeclRegionScope);
4716 } else {
John McCall4fa53422009-10-01 00:25:31 +00004717 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00004718 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00004719
4720 // Link the anonymous namespace into its parent.
4721 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00004722 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00004723 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4724 PrevDecl = TU->getAnonymousNamespace();
4725 TU->setAnonymousNamespace(Namespc);
4726 } else {
4727 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4728 PrevDecl = ND->getAnonymousNamespace();
4729 ND->setAnonymousNamespace(Namespc);
4730 }
4731
4732 // Link the anonymous namespace with its previous declaration.
4733 if (PrevDecl) {
4734 assert(PrevDecl->isAnonymousNamespace());
4735 assert(!PrevDecl->getNextNamespace());
4736 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4737 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004738
4739 if (Namespc->isInline() != PrevDecl->isInline()) {
4740 // inline-ness must match
4741 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4742 << Namespc->isInline();
4743 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4744 Namespc->setInvalidDecl();
4745 // Recover by ignoring the new namespace's inline status.
4746 Namespc->setInline(PrevDecl->isInline());
4747 }
John McCall0db42252009-12-16 02:06:49 +00004748 }
John McCall4fa53422009-10-01 00:25:31 +00004749
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00004750 CurContext->addDecl(Namespc);
4751
John McCall4fa53422009-10-01 00:25:31 +00004752 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4753 // behaves as if it were replaced by
4754 // namespace unique { /* empty body */ }
4755 // using namespace unique;
4756 // namespace unique { namespace-body }
4757 // where all occurrences of 'unique' in a translation unit are
4758 // replaced by the same identifier and this identifier differs
4759 // from all other identifiers in the entire program.
4760
4761 // We just create the namespace with an empty name and then add an
4762 // implicit using declaration, just like the standard suggests.
4763 //
4764 // CodeGen enforces the "universally unique" aspect by giving all
4765 // declarations semantically contained within an anonymous
4766 // namespace internal linkage.
4767
John McCall0db42252009-12-16 02:06:49 +00004768 if (!PrevDecl) {
4769 UsingDirectiveDecl* UD
4770 = UsingDirectiveDecl::Create(Context, CurContext,
4771 /* 'using' */ LBrace,
4772 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00004773 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00004774 /* identifier */ SourceLocation(),
4775 Namespc,
4776 /* Ancestor */ CurContext);
4777 UD->setImplicit();
4778 CurContext->addDecl(UD);
4779 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004780 }
4781
4782 // Although we could have an invalid decl (i.e. the namespace name is a
4783 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00004784 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4785 // for the namespace has the declarations that showed up in that particular
4786 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00004787 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00004788 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004789}
4790
Sebastian Redla6602e92009-11-23 15:34:23 +00004791/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4792/// is a namespace alias, returns the namespace it points to.
4793static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4794 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4795 return AD->getNamespace();
4796 return dyn_cast_or_null<NamespaceDecl>(D);
4797}
4798
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004799/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4800/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00004801void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004802 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4803 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004804 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004805 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00004806 if (Namespc->hasAttr<VisibilityAttr>())
4807 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004808}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004809
John McCall28a0cf72010-08-25 07:42:41 +00004810CXXRecordDecl *Sema::getStdBadAlloc() const {
4811 return cast_or_null<CXXRecordDecl>(
4812 StdBadAlloc.get(Context.getExternalSource()));
4813}
4814
4815NamespaceDecl *Sema::getStdNamespace() const {
4816 return cast_or_null<NamespaceDecl>(
4817 StdNamespace.get(Context.getExternalSource()));
4818}
4819
Douglas Gregorcdf87022010-06-29 17:53:46 +00004820/// \brief Retrieve the special "std" namespace, which may require us to
4821/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004822NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00004823 if (!StdNamespace) {
4824 // The "std" namespace has not yet been defined, so build one implicitly.
4825 StdNamespace = NamespaceDecl::Create(Context,
4826 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004827 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00004828 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004829 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004830 }
4831
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004832 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004833}
4834
Douglas Gregora172e082011-03-26 22:25:30 +00004835/// \brief Determine whether a using statement is in a context where it will be
4836/// apply in all contexts.
4837static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4838 switch (CurContext->getDeclKind()) {
4839 case Decl::TranslationUnit:
4840 return true;
4841 case Decl::LinkageSpec:
4842 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4843 default:
4844 return false;
4845 }
4846}
4847
John McCall48871652010-08-21 09:40:31 +00004848Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00004849 SourceLocation UsingLoc,
4850 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004851 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004852 SourceLocation IdentLoc,
4853 IdentifierInfo *NamespcName,
4854 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00004855 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4856 assert(NamespcName && "Invalid NamespcName.");
4857 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00004858
4859 // This can only happen along a recovery path.
4860 while (S->getFlags() & Scope::TemplateParamScope)
4861 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00004862 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00004863
Douglas Gregor889ceb72009-02-03 19:21:40 +00004864 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00004865 NestedNameSpecifier *Qualifier = 0;
4866 if (SS.isSet())
4867 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4868
Douglas Gregor34074322009-01-14 22:20:51 +00004869 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004870 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4871 LookupParsedName(R, S, &SS);
4872 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004873 return 0;
John McCall27b18f82009-11-17 02:14:36 +00004874
Douglas Gregorcdf87022010-06-29 17:53:46 +00004875 if (R.empty()) {
4876 // Allow "using namespace std;" or "using namespace ::std;" even if
4877 // "std" hasn't been defined yet, for GCC compatibility.
4878 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4879 NamespcName->isStr("std")) {
4880 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004881 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00004882 R.resolveKind();
4883 }
4884 // Otherwise, attempt typo correction.
4885 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4886 CTC_NoKeywords, 0)) {
4887 if (R.getAsSingle<NamespaceDecl>() ||
4888 R.getAsSingle<NamespaceAliasDecl>()) {
4889 if (DeclContext *DC = computeDeclContext(SS, false))
4890 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4891 << NamespcName << DC << Corrected << SS.getRange()
4892 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4893 else
4894 Diag(IdentLoc, diag::err_using_directive_suggest)
4895 << NamespcName << Corrected
4896 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4897 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4898 << Corrected;
4899
4900 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004901 } else {
4902 R.clear();
4903 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004904 }
4905 }
4906 }
4907
John McCall9f3059a2009-10-09 21:13:30 +00004908 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00004909 NamedDecl *Named = R.getFoundDecl();
4910 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4911 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00004912 // C++ [namespace.udir]p1:
4913 // A using-directive specifies that the names in the nominated
4914 // namespace can be used in the scope in which the
4915 // using-directive appears after the using-directive. During
4916 // unqualified name lookup (3.4.1), the names appear as if they
4917 // were declared in the nearest enclosing namespace which
4918 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00004919 // namespace. [Note: in this context, "contains" means "contains
4920 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00004921
4922 // Find enclosing context containing both using-directive and
4923 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00004924 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004925 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4926 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4927 CommonAncestor = CommonAncestor->getParent();
4928
Sebastian Redla6602e92009-11-23 15:34:23 +00004929 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00004930 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00004931 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004932
Douglas Gregora172e082011-03-26 22:25:30 +00004933 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00004934 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004935 Diag(IdentLoc, diag::warn_using_directive_in_header);
4936 }
4937
Douglas Gregor889ceb72009-02-03 19:21:40 +00004938 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004939 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00004940 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00004941 }
4942
Douglas Gregor889ceb72009-02-03 19:21:40 +00004943 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00004944 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00004945}
4946
4947void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4948 // If scope has associated entity, then using directive is at namespace
4949 // or translation unit scope. We add UsingDirectiveDecls, into
4950 // it's lookup structure.
4951 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004952 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004953 else
4954 // Otherwise it is block-sope. using-directives will affect lookup
4955 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00004956 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004957}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004958
Douglas Gregorfec52632009-06-20 00:51:54 +00004959
John McCall48871652010-08-21 09:40:31 +00004960Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00004961 AccessSpecifier AS,
4962 bool HasUsingKeyword,
4963 SourceLocation UsingLoc,
4964 CXXScopeSpec &SS,
4965 UnqualifiedId &Name,
4966 AttributeList *AttrList,
4967 bool IsTypeName,
4968 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004969 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004970
Douglas Gregor220f4272009-11-04 16:30:06 +00004971 switch (Name.getKind()) {
4972 case UnqualifiedId::IK_Identifier:
4973 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004974 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004975 case UnqualifiedId::IK_ConversionFunctionId:
4976 break;
4977
4978 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004979 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004980 // C++0x inherited constructors.
4981 if (getLangOptions().CPlusPlus0x) break;
4982
Douglas Gregor220f4272009-11-04 16:30:06 +00004983 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4984 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004985 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004986
4987 case UnqualifiedId::IK_DestructorName:
4988 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4989 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004990 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004991
4992 case UnqualifiedId::IK_TemplateId:
4993 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4994 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00004995 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004996 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004997
4998 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4999 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005000 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005001 return 0;
John McCall3969e302009-12-08 07:46:18 +00005002
John McCalla0097262009-12-11 02:10:03 +00005003 // Warn about using declarations.
5004 // TODO: store that the declaration was written without 'using' and
5005 // talk about access decls instead of using decls in the
5006 // diagnostics.
5007 if (!HasUsingKeyword) {
5008 UsingLoc = Name.getSourceRange().getBegin();
5009
5010 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005011 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005012 }
5013
Douglas Gregorc4356532010-12-16 00:46:58 +00005014 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5015 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5016 return 0;
5017
John McCall3f746822009-11-17 05:59:44 +00005018 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005019 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005020 /* IsInstantiation */ false,
5021 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005022 if (UD)
5023 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005024
John McCall48871652010-08-21 09:40:31 +00005025 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005026}
5027
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005028/// \brief Determine whether a using declaration considers the given
5029/// declarations as "equivalent", e.g., if they are redeclarations of
5030/// the same entity or are both typedefs of the same type.
5031static bool
5032IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5033 bool &SuppressRedeclaration) {
5034 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5035 SuppressRedeclaration = false;
5036 return true;
5037 }
5038
Richard Smithdda56e42011-04-15 14:24:37 +00005039 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5040 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005041 SuppressRedeclaration = true;
5042 return Context.hasSameType(TD1->getUnderlyingType(),
5043 TD2->getUnderlyingType());
5044 }
5045
5046 return false;
5047}
5048
5049
John McCall84d87672009-12-10 09:41:52 +00005050/// Determines whether to create a using shadow decl for a particular
5051/// decl, given the set of decls existing prior to this using lookup.
5052bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5053 const LookupResult &Previous) {
5054 // Diagnose finding a decl which is not from a base class of the
5055 // current class. We do this now because there are cases where this
5056 // function will silently decide not to build a shadow decl, which
5057 // will pre-empt further diagnostics.
5058 //
5059 // We don't need to do this in C++0x because we do the check once on
5060 // the qualifier.
5061 //
5062 // FIXME: diagnose the following if we care enough:
5063 // struct A { int foo; };
5064 // struct B : A { using A::foo; };
5065 // template <class T> struct C : A {};
5066 // template <class T> struct D : C<T> { using B::foo; } // <---
5067 // This is invalid (during instantiation) in C++03 because B::foo
5068 // resolves to the using decl in B, which is not a base class of D<T>.
5069 // We can't diagnose it immediately because C<T> is an unknown
5070 // specialization. The UsingShadowDecl in D<T> then points directly
5071 // to A::foo, which will look well-formed when we instantiate.
5072 // The right solution is to not collapse the shadow-decl chain.
5073 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5074 DeclContext *OrigDC = Orig->getDeclContext();
5075
5076 // Handle enums and anonymous structs.
5077 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5078 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5079 while (OrigRec->isAnonymousStructOrUnion())
5080 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5081
5082 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5083 if (OrigDC == CurContext) {
5084 Diag(Using->getLocation(),
5085 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005086 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005087 Diag(Orig->getLocation(), diag::note_using_decl_target);
5088 return true;
5089 }
5090
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005091 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005092 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005093 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005094 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005095 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005096 Diag(Orig->getLocation(), diag::note_using_decl_target);
5097 return true;
5098 }
5099 }
5100
5101 if (Previous.empty()) return false;
5102
5103 NamedDecl *Target = Orig;
5104 if (isa<UsingShadowDecl>(Target))
5105 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5106
John McCalla17e83e2009-12-11 02:33:26 +00005107 // If the target happens to be one of the previous declarations, we
5108 // don't have a conflict.
5109 //
5110 // FIXME: but we might be increasing its access, in which case we
5111 // should redeclare it.
5112 NamedDecl *NonTag = 0, *Tag = 0;
5113 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5114 I != E; ++I) {
5115 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005116 bool Result;
5117 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5118 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005119
5120 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5121 }
5122
John McCall84d87672009-12-10 09:41:52 +00005123 if (Target->isFunctionOrFunctionTemplate()) {
5124 FunctionDecl *FD;
5125 if (isa<FunctionTemplateDecl>(Target))
5126 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5127 else
5128 FD = cast<FunctionDecl>(Target);
5129
5130 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005131 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005132 case Ovl_Overload:
5133 return false;
5134
5135 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005136 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005137 break;
5138
5139 // We found a decl with the exact signature.
5140 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005141 // If we're in a record, we want to hide the target, so we
5142 // return true (without a diagnostic) to tell the caller not to
5143 // build a shadow decl.
5144 if (CurContext->isRecord())
5145 return true;
5146
5147 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005148 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005149 break;
5150 }
5151
5152 Diag(Target->getLocation(), diag::note_using_decl_target);
5153 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5154 return true;
5155 }
5156
5157 // Target is not a function.
5158
John McCall84d87672009-12-10 09:41:52 +00005159 if (isa<TagDecl>(Target)) {
5160 // No conflict between a tag and a non-tag.
5161 if (!Tag) return false;
5162
John McCalle29c5cd2009-12-10 19:51:03 +00005163 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005164 Diag(Target->getLocation(), diag::note_using_decl_target);
5165 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5166 return true;
5167 }
5168
5169 // No conflict between a tag and a non-tag.
5170 if (!NonTag) return false;
5171
John McCalle29c5cd2009-12-10 19:51:03 +00005172 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005173 Diag(Target->getLocation(), diag::note_using_decl_target);
5174 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5175 return true;
5176}
5177
John McCall3f746822009-11-17 05:59:44 +00005178/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005179UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005180 UsingDecl *UD,
5181 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005182
5183 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005184 NamedDecl *Target = Orig;
5185 if (isa<UsingShadowDecl>(Target)) {
5186 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5187 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005188 }
5189
5190 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005191 = UsingShadowDecl::Create(Context, CurContext,
5192 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005193 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005194
5195 Shadow->setAccess(UD->getAccess());
5196 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5197 Shadow->setInvalidDecl();
5198
John McCall3f746822009-11-17 05:59:44 +00005199 if (S)
John McCall3969e302009-12-08 07:46:18 +00005200 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005201 else
John McCall3969e302009-12-08 07:46:18 +00005202 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005203
John McCall3969e302009-12-08 07:46:18 +00005204
John McCall84d87672009-12-10 09:41:52 +00005205 return Shadow;
5206}
John McCall3969e302009-12-08 07:46:18 +00005207
John McCall84d87672009-12-10 09:41:52 +00005208/// Hides a using shadow declaration. This is required by the current
5209/// using-decl implementation when a resolvable using declaration in a
5210/// class is followed by a declaration which would hide or override
5211/// one or more of the using decl's targets; for example:
5212///
5213/// struct Base { void foo(int); };
5214/// struct Derived : Base {
5215/// using Base::foo;
5216/// void foo(int);
5217/// };
5218///
5219/// The governing language is C++03 [namespace.udecl]p12:
5220///
5221/// When a using-declaration brings names from a base class into a
5222/// derived class scope, member functions in the derived class
5223/// override and/or hide member functions with the same name and
5224/// parameter types in a base class (rather than conflicting).
5225///
5226/// There are two ways to implement this:
5227/// (1) optimistically create shadow decls when they're not hidden
5228/// by existing declarations, or
5229/// (2) don't create any shadow decls (or at least don't make them
5230/// visible) until we've fully parsed/instantiated the class.
5231/// The problem with (1) is that we might have to retroactively remove
5232/// a shadow decl, which requires several O(n) operations because the
5233/// decl structures are (very reasonably) not designed for removal.
5234/// (2) avoids this but is very fiddly and phase-dependent.
5235void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005236 if (Shadow->getDeclName().getNameKind() ==
5237 DeclarationName::CXXConversionFunctionName)
5238 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5239
John McCall84d87672009-12-10 09:41:52 +00005240 // Remove it from the DeclContext...
5241 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005242
John McCall84d87672009-12-10 09:41:52 +00005243 // ...and the scope, if applicable...
5244 if (S) {
John McCall48871652010-08-21 09:40:31 +00005245 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005246 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005247 }
5248
John McCall84d87672009-12-10 09:41:52 +00005249 // ...and the using decl.
5250 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5251
5252 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005253 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005254}
5255
John McCalle61f2ba2009-11-18 02:36:19 +00005256/// Builds a using declaration.
5257///
5258/// \param IsInstantiation - Whether this call arises from an
5259/// instantiation of an unresolved using declaration. We treat
5260/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005261NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5262 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005263 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005264 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005265 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005266 bool IsInstantiation,
5267 bool IsTypeName,
5268 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005269 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005270 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005271 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005272
Anders Carlssonf038fc22009-08-28 05:49:21 +00005273 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005274
Anders Carlsson59140b32009-08-28 03:16:11 +00005275 if (SS.isEmpty()) {
5276 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005277 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005278 }
Mike Stump11289f42009-09-09 15:08:12 +00005279
John McCall84d87672009-12-10 09:41:52 +00005280 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005281 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005282 ForRedeclaration);
5283 Previous.setHideTags(false);
5284 if (S) {
5285 LookupName(Previous, S);
5286
5287 // It is really dumb that we have to do this.
5288 LookupResult::Filter F = Previous.makeFilter();
5289 while (F.hasNext()) {
5290 NamedDecl *D = F.next();
5291 if (!isDeclInScope(D, CurContext, S))
5292 F.erase();
5293 }
5294 F.done();
5295 } else {
5296 assert(IsInstantiation && "no scope in non-instantiation");
5297 assert(CurContext->isRecord() && "scope not record in instantiation");
5298 LookupQualifiedName(Previous, CurContext);
5299 }
5300
John McCall84d87672009-12-10 09:41:52 +00005301 // Check for invalid redeclarations.
5302 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5303 return 0;
5304
5305 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005306 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5307 return 0;
5308
John McCall84c16cf2009-11-12 03:15:40 +00005309 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005310 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005311 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005312 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005313 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005314 // FIXME: not all declaration name kinds are legal here
5315 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5316 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005317 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005318 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005319 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005320 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5321 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005322 }
John McCallb96ec562009-12-04 22:46:56 +00005323 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005324 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5325 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005326 }
John McCallb96ec562009-12-04 22:46:56 +00005327 D->setAccess(AS);
5328 CurContext->addDecl(D);
5329
5330 if (!LookupContext) return D;
5331 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005332
John McCall0b66eb32010-05-01 00:40:08 +00005333 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005334 UD->setInvalidDecl();
5335 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005336 }
5337
Sebastian Redl08905022011-02-05 19:23:19 +00005338 // Constructor inheriting using decls get special treatment.
5339 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005340 if (CheckInheritedConstructorUsingDecl(UD))
5341 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005342 return UD;
5343 }
5344
5345 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005346
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005347 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetefb1af92011-05-23 03:43:44 +00005348 R.setUsingDeclaration(true);
John McCalle61f2ba2009-11-18 02:36:19 +00005349
John McCall3969e302009-12-08 07:46:18 +00005350 // Unlike most lookups, we don't always want to hide tag
5351 // declarations: tag names are visible through the using declaration
5352 // even if hidden by ordinary names, *except* in a dependent context
5353 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005354 if (!IsInstantiation)
5355 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005356
John McCall27b18f82009-11-17 02:14:36 +00005357 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005358
John McCall9f3059a2009-10-09 21:13:30 +00005359 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005360 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005361 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005362 UD->setInvalidDecl();
5363 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005364 }
5365
John McCallb96ec562009-12-04 22:46:56 +00005366 if (R.isAmbiguous()) {
5367 UD->setInvalidDecl();
5368 return UD;
5369 }
Mike Stump11289f42009-09-09 15:08:12 +00005370
John McCalle61f2ba2009-11-18 02:36:19 +00005371 if (IsTypeName) {
5372 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005373 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005374 Diag(IdentLoc, diag::err_using_typename_non_type);
5375 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5376 Diag((*I)->getUnderlyingDecl()->getLocation(),
5377 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005378 UD->setInvalidDecl();
5379 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005380 }
5381 } else {
5382 // If we asked for a non-typename and we got a type, error out,
5383 // but only if this is an instantiation of an unresolved using
5384 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005385 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005386 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5387 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005388 UD->setInvalidDecl();
5389 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005390 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005391 }
5392
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005393 // C++0x N2914 [namespace.udecl]p6:
5394 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005395 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005396 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5397 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005398 UD->setInvalidDecl();
5399 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005400 }
Mike Stump11289f42009-09-09 15:08:12 +00005401
John McCall84d87672009-12-10 09:41:52 +00005402 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5403 if (!CheckUsingShadowDecl(UD, *I, Previous))
5404 BuildUsingShadowDecl(S, UD, *I);
5405 }
John McCall3f746822009-11-17 05:59:44 +00005406
5407 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005408}
5409
Sebastian Redl08905022011-02-05 19:23:19 +00005410/// Additional checks for a using declaration referring to a constructor name.
5411bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5412 if (UD->isTypeName()) {
5413 // FIXME: Cannot specify typename when specifying constructor
5414 return true;
5415 }
5416
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005417 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00005418 assert(SourceType &&
5419 "Using decl naming constructor doesn't have type in scope spec.");
5420 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5421
5422 // Check whether the named type is a direct base class.
5423 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5424 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5425 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5426 BaseIt != BaseE; ++BaseIt) {
5427 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5428 if (CanonicalSourceType == BaseType)
5429 break;
5430 }
5431
5432 if (BaseIt == BaseE) {
5433 // Did not find SourceType in the bases.
5434 Diag(UD->getUsingLocation(),
5435 diag::err_using_decl_constructor_not_in_direct_base)
5436 << UD->getNameInfo().getSourceRange()
5437 << QualType(SourceType, 0) << TargetClass;
5438 return true;
5439 }
5440
5441 BaseIt->setInheritConstructors();
5442
5443 return false;
5444}
5445
John McCall84d87672009-12-10 09:41:52 +00005446/// Checks that the given using declaration is not an invalid
5447/// redeclaration. Note that this is checking only for the using decl
5448/// itself, not for any ill-formedness among the UsingShadowDecls.
5449bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5450 bool isTypeName,
5451 const CXXScopeSpec &SS,
5452 SourceLocation NameLoc,
5453 const LookupResult &Prev) {
5454 // C++03 [namespace.udecl]p8:
5455 // C++0x [namespace.udecl]p10:
5456 // A using-declaration is a declaration and can therefore be used
5457 // repeatedly where (and only where) multiple declarations are
5458 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00005459 //
John McCall032092f2010-11-29 18:01:58 +00005460 // That's in non-member contexts.
5461 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00005462 return false;
5463
5464 NestedNameSpecifier *Qual
5465 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5466
5467 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5468 NamedDecl *D = *I;
5469
5470 bool DTypename;
5471 NestedNameSpecifier *DQual;
5472 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5473 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005474 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005475 } else if (UnresolvedUsingValueDecl *UD
5476 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5477 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005478 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005479 } else if (UnresolvedUsingTypenameDecl *UD
5480 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5481 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005482 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005483 } else continue;
5484
5485 // using decls differ if one says 'typename' and the other doesn't.
5486 // FIXME: non-dependent using decls?
5487 if (isTypeName != DTypename) continue;
5488
5489 // using decls differ if they name different scopes (but note that
5490 // template instantiation can cause this check to trigger when it
5491 // didn't before instantiation).
5492 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5493 Context.getCanonicalNestedNameSpecifier(DQual))
5494 continue;
5495
5496 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00005497 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00005498 return true;
5499 }
5500
5501 return false;
5502}
5503
John McCall3969e302009-12-08 07:46:18 +00005504
John McCallb96ec562009-12-04 22:46:56 +00005505/// Checks that the given nested-name qualifier used in a using decl
5506/// in the current context is appropriately related to the current
5507/// scope. If an error is found, diagnoses it and returns true.
5508bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5509 const CXXScopeSpec &SS,
5510 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00005511 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005512
John McCall3969e302009-12-08 07:46:18 +00005513 if (!CurContext->isRecord()) {
5514 // C++03 [namespace.udecl]p3:
5515 // C++0x [namespace.udecl]p8:
5516 // A using-declaration for a class member shall be a member-declaration.
5517
5518 // If we weren't able to compute a valid scope, it must be a
5519 // dependent class scope.
5520 if (!NamedContext || NamedContext->isRecord()) {
5521 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5522 << SS.getRange();
5523 return true;
5524 }
5525
5526 // Otherwise, everything is known to be fine.
5527 return false;
5528 }
5529
5530 // The current scope is a record.
5531
5532 // If the named context is dependent, we can't decide much.
5533 if (!NamedContext) {
5534 // FIXME: in C++0x, we can diagnose if we can prove that the
5535 // nested-name-specifier does not refer to a base class, which is
5536 // still possible in some cases.
5537
5538 // Otherwise we have to conservatively report that things might be
5539 // okay.
5540 return false;
5541 }
5542
5543 if (!NamedContext->isRecord()) {
5544 // Ideally this would point at the last name in the specifier,
5545 // but we don't have that level of source info.
5546 Diag(SS.getRange().getBegin(),
5547 diag::err_using_decl_nested_name_specifier_is_not_class)
5548 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5549 return true;
5550 }
5551
Douglas Gregor7c842292010-12-21 07:41:49 +00005552 if (!NamedContext->isDependentContext() &&
5553 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5554 return true;
5555
John McCall3969e302009-12-08 07:46:18 +00005556 if (getLangOptions().CPlusPlus0x) {
5557 // C++0x [namespace.udecl]p3:
5558 // In a using-declaration used as a member-declaration, the
5559 // nested-name-specifier shall name a base class of the class
5560 // being defined.
5561
5562 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5563 cast<CXXRecordDecl>(NamedContext))) {
5564 if (CurContext == NamedContext) {
5565 Diag(NameLoc,
5566 diag::err_using_decl_nested_name_specifier_is_current_class)
5567 << SS.getRange();
5568 return true;
5569 }
5570
5571 Diag(SS.getRange().getBegin(),
5572 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5573 << (NestedNameSpecifier*) SS.getScopeRep()
5574 << cast<CXXRecordDecl>(CurContext)
5575 << SS.getRange();
5576 return true;
5577 }
5578
5579 return false;
5580 }
5581
5582 // C++03 [namespace.udecl]p4:
5583 // A using-declaration used as a member-declaration shall refer
5584 // to a member of a base class of the class being defined [etc.].
5585
5586 // Salient point: SS doesn't have to name a base class as long as
5587 // lookup only finds members from base classes. Therefore we can
5588 // diagnose here only if we can prove that that can't happen,
5589 // i.e. if the class hierarchies provably don't intersect.
5590
5591 // TODO: it would be nice if "definitely valid" results were cached
5592 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5593 // need to be repeated.
5594
5595 struct UserData {
5596 llvm::DenseSet<const CXXRecordDecl*> Bases;
5597
5598 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5599 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5600 Data->Bases.insert(Base);
5601 return true;
5602 }
5603
5604 bool hasDependentBases(const CXXRecordDecl *Class) {
5605 return !Class->forallBases(collect, this);
5606 }
5607
5608 /// Returns true if the base is dependent or is one of the
5609 /// accumulated base classes.
5610 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5611 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5612 return !Data->Bases.count(Base);
5613 }
5614
5615 bool mightShareBases(const CXXRecordDecl *Class) {
5616 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5617 }
5618 };
5619
5620 UserData Data;
5621
5622 // Returns false if we find a dependent base.
5623 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5624 return false;
5625
5626 // Returns false if the class has a dependent base or if it or one
5627 // of its bases is present in the base set of the current context.
5628 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5629 return false;
5630
5631 Diag(SS.getRange().getBegin(),
5632 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5633 << (NestedNameSpecifier*) SS.getScopeRep()
5634 << cast<CXXRecordDecl>(CurContext)
5635 << SS.getRange();
5636
5637 return true;
John McCallb96ec562009-12-04 22:46:56 +00005638}
5639
Richard Smithdda56e42011-04-15 14:24:37 +00005640Decl *Sema::ActOnAliasDeclaration(Scope *S,
5641 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005642 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00005643 SourceLocation UsingLoc,
5644 UnqualifiedId &Name,
5645 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00005646 // Skip up to the relevant declaration scope.
5647 while (S->getFlags() & Scope::TemplateParamScope)
5648 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00005649 assert((S->getFlags() & Scope::DeclScope) &&
5650 "got alias-declaration outside of declaration scope");
5651
5652 if (Type.isInvalid())
5653 return 0;
5654
5655 bool Invalid = false;
5656 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5657 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00005658 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00005659
5660 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5661 return 0;
5662
5663 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005664 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00005665 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005666 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5667 TInfo->getTypeLoc().getBeginLoc());
5668 }
Richard Smithdda56e42011-04-15 14:24:37 +00005669
5670 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5671 LookupName(Previous, S);
5672
5673 // Warn about shadowing the name of a template parameter.
5674 if (Previous.isSingleResult() &&
5675 Previous.getFoundDecl()->isTemplateParameter()) {
5676 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5677 Previous.getFoundDecl()))
5678 Invalid = true;
5679 Previous.clear();
5680 }
5681
5682 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5683 "name in alias declaration must be an identifier");
5684 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5685 Name.StartLocation,
5686 Name.Identifier, TInfo);
5687
5688 NewTD->setAccess(AS);
5689
5690 if (Invalid)
5691 NewTD->setInvalidDecl();
5692
Richard Smith3f1b5d02011-05-05 21:57:07 +00005693 CheckTypedefForVariablyModifiedType(S, NewTD);
5694 Invalid |= NewTD->isInvalidDecl();
5695
Richard Smithdda56e42011-04-15 14:24:37 +00005696 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005697
5698 NamedDecl *NewND;
5699 if (TemplateParamLists.size()) {
5700 TypeAliasTemplateDecl *OldDecl = 0;
5701 TemplateParameterList *OldTemplateParams = 0;
5702
5703 if (TemplateParamLists.size() != 1) {
5704 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5705 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5706 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5707 }
5708 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5709
5710 // Only consider previous declarations in the same scope.
5711 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5712 /*ExplicitInstantiationOrSpecialization*/false);
5713 if (!Previous.empty()) {
5714 Redeclaration = true;
5715
5716 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5717 if (!OldDecl && !Invalid) {
5718 Diag(UsingLoc, diag::err_redefinition_different_kind)
5719 << Name.Identifier;
5720
5721 NamedDecl *OldD = Previous.getRepresentativeDecl();
5722 if (OldD->getLocation().isValid())
5723 Diag(OldD->getLocation(), diag::note_previous_definition);
5724
5725 Invalid = true;
5726 }
5727
5728 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5729 if (TemplateParameterListsAreEqual(TemplateParams,
5730 OldDecl->getTemplateParameters(),
5731 /*Complain=*/true,
5732 TPL_TemplateMatch))
5733 OldTemplateParams = OldDecl->getTemplateParameters();
5734 else
5735 Invalid = true;
5736
5737 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5738 if (!Invalid &&
5739 !Context.hasSameType(OldTD->getUnderlyingType(),
5740 NewTD->getUnderlyingType())) {
5741 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5742 // but we can't reasonably accept it.
5743 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5744 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5745 if (OldTD->getLocation().isValid())
5746 Diag(OldTD->getLocation(), diag::note_previous_definition);
5747 Invalid = true;
5748 }
5749 }
5750 }
5751
5752 // Merge any previous default template arguments into our parameters,
5753 // and check the parameter list.
5754 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5755 TPC_TypeAliasTemplate))
5756 return 0;
5757
5758 TypeAliasTemplateDecl *NewDecl =
5759 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5760 Name.Identifier, TemplateParams,
5761 NewTD);
5762
5763 NewDecl->setAccess(AS);
5764
5765 if (Invalid)
5766 NewDecl->setInvalidDecl();
5767 else if (OldDecl)
5768 NewDecl->setPreviousDeclaration(OldDecl);
5769
5770 NewND = NewDecl;
5771 } else {
5772 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5773 NewND = NewTD;
5774 }
Richard Smithdda56e42011-04-15 14:24:37 +00005775
5776 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00005777 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00005778
Richard Smith3f1b5d02011-05-05 21:57:07 +00005779 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00005780}
5781
John McCall48871652010-08-21 09:40:31 +00005782Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005783 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005784 SourceLocation AliasLoc,
5785 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005786 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005787 SourceLocation IdentLoc,
5788 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00005789
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005790 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005791 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5792 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005793
Anders Carlssondca83c42009-03-28 06:23:46 +00005794 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00005795 NamedDecl *PrevDecl
5796 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5797 ForRedeclaration);
5798 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5799 PrevDecl = 0;
5800
5801 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005802 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00005803 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005804 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00005805 // FIXME: At some point, we'll want to create the (redundant)
5806 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00005807 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00005808 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00005809 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005810 }
Mike Stump11289f42009-09-09 15:08:12 +00005811
Anders Carlssondca83c42009-03-28 06:23:46 +00005812 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5813 diag::err_redefinition_different_kind;
5814 Diag(AliasLoc, DiagID) << Alias;
5815 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00005816 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00005817 }
5818
John McCall27b18f82009-11-17 02:14:36 +00005819 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005820 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005821
John McCall9f3059a2009-10-09 21:13:30 +00005822 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005823 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5824 CTC_NoKeywords, 0)) {
5825 if (R.getAsSingle<NamespaceDecl>() ||
5826 R.getAsSingle<NamespaceAliasDecl>()) {
5827 if (DeclContext *DC = computeDeclContext(SS, false))
5828 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5829 << Ident << DC << Corrected << SS.getRange()
5830 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5831 else
5832 Diag(IdentLoc, diag::err_using_directive_suggest)
5833 << Ident << Corrected
5834 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5835
5836 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5837 << Corrected;
5838
5839 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00005840 } else {
5841 R.clear();
5842 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005843 }
5844 }
5845
5846 if (R.empty()) {
5847 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005848 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005849 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00005850 }
Mike Stump11289f42009-09-09 15:08:12 +00005851
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005852 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00005853 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00005854 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00005855 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00005856
John McCalld8d0d432010-02-16 06:53:13 +00005857 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00005858 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00005859}
5860
Douglas Gregora57478e2010-05-01 15:04:51 +00005861namespace {
5862 /// \brief Scoped object used to handle the state changes required in Sema
5863 /// to implicitly define the body of a C++ member function;
5864 class ImplicitlyDefinedFunctionScope {
5865 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00005866 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00005867
5868 public:
5869 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00005870 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00005871 {
Douglas Gregora57478e2010-05-01 15:04:51 +00005872 S.PushFunctionScope();
5873 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5874 }
5875
5876 ~ImplicitlyDefinedFunctionScope() {
5877 S.PopExpressionEvaluationContext();
5878 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00005879 }
5880 };
5881}
5882
Sebastian Redlc15c3262010-09-13 22:02:47 +00005883static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
5884 CXXRecordDecl *D) {
5885 ASTContext &Context = Self.Context;
5886 QualType ClassType = Context.getTypeDeclType(D);
5887 DeclarationName ConstructorName
5888 = Context.DeclarationNames.getCXXConstructorName(
5889 Context.getCanonicalType(ClassType.getUnqualifiedType()));
5890
5891 DeclContext::lookup_const_iterator Con, ConEnd;
5892 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
5893 Con != ConEnd; ++Con) {
5894 // FIXME: In C++0x, a constructor template can be a default constructor.
5895 if (isa<FunctionTemplateDecl>(*Con))
5896 continue;
5897
5898 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
5899 if (Constructor->isDefaultConstructor())
5900 return Constructor;
5901 }
5902 return 0;
5903}
5904
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005905Sema::ImplicitExceptionSpecification
5906Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00005907 // C++ [except.spec]p14:
5908 // An implicitly declared special member function (Clause 12) shall have an
5909 // exception-specification. [...]
5910 ImplicitExceptionSpecification ExceptSpec(Context);
5911
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005912 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005913 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5914 BEnd = ClassDecl->bases_end();
5915 B != BEnd; ++B) {
5916 if (B->isVirtual()) // Handled below.
5917 continue;
5918
Douglas Gregor9672f922010-07-03 00:47:00 +00005919 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5920 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Huntea6f0322011-05-11 22:34:38 +00005921 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005922 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00005923 else if (CXXConstructorDecl *Constructor
5924 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005925 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005926 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005927 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005928
5929 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005930 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5931 BEnd = ClassDecl->vbases_end();
5932 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00005933 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5934 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Huntea6f0322011-05-11 22:34:38 +00005935 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005936 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5937 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00005938 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005939 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005940 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005941 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005942
5943 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005944 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5945 FEnd = ClassDecl->field_end();
5946 F != FEnd; ++F) {
5947 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00005948 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5949 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Alexis Huntea6f0322011-05-11 22:34:38 +00005950 if (FieldClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005951 ExceptSpec.CalledDecl(
5952 DeclareImplicitDefaultConstructor(FieldClassDecl));
5953 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00005954 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005955 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005956 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005957 }
John McCalldb40c7f2010-12-14 08:05:40 +00005958
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005959 return ExceptSpec;
5960}
5961
5962CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5963 CXXRecordDecl *ClassDecl) {
5964 // C++ [class.ctor]p5:
5965 // A default constructor for a class X is a constructor of class X
5966 // that can be called without an argument. If there is no
5967 // user-declared constructor for class X, a default constructor is
5968 // implicitly declared. An implicitly-declared default constructor
5969 // is an inline public member of its class.
5970 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5971 "Should not build implicit default constructor!");
5972
5973 ImplicitExceptionSpecification Spec =
5974 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5975 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005976
Douglas Gregor6d880b12010-07-01 22:31:05 +00005977 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005978 CanQualType ClassType
5979 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005980 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005981 DeclarationName Name
5982 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005983 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005984 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00005985 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005986 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005987 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005988 /*TInfo=*/0,
5989 /*isExplicit=*/false,
5990 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005991 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005992 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00005993 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005994 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00005995 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00005996
5997 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00005998 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5999
Douglas Gregor0be31a22010-07-02 17:43:08 +00006000 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00006001 PushOnScopeChains(DefaultCon, S, false);
6002 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00006003
6004 if (ShouldDeleteDefaultConstructor(DefaultCon))
6005 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00006006
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006007 return DefaultCon;
6008}
6009
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006010void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6011 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006012 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00006013 !Constructor->isUsed(false) && !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006014 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006015
Anders Carlsson423f5d82010-04-23 16:04:08 +00006016 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006017 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006018
Douglas Gregora57478e2010-05-01 15:04:51 +00006019 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006020 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006021 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006022 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006023 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006024 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006025 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006026 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006027 }
Douglas Gregor73193272010-09-20 16:48:21 +00006028
6029 SourceLocation Loc = Constructor->getLocation();
6030 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6031
6032 Constructor->setUsed();
6033 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006034
6035 if (ASTMutationListener *L = getASTMutationListener()) {
6036 L->CompletedImplicitDefinition(Constructor);
6037 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006038}
6039
Sebastian Redl08905022011-02-05 19:23:19 +00006040void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6041 // We start with an initial pass over the base classes to collect those that
6042 // inherit constructors from. If there are none, we can forgo all further
6043 // processing.
6044 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6045 BasesVector BasesToInheritFrom;
6046 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6047 BaseE = ClassDecl->bases_end();
6048 BaseIt != BaseE; ++BaseIt) {
6049 if (BaseIt->getInheritConstructors()) {
6050 QualType Base = BaseIt->getType();
6051 if (Base->isDependentType()) {
6052 // If we inherit constructors from anything that is dependent, just
6053 // abort processing altogether. We'll get another chance for the
6054 // instantiations.
6055 return;
6056 }
6057 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6058 }
6059 }
6060 if (BasesToInheritFrom.empty())
6061 return;
6062
6063 // Now collect the constructors that we already have in the current class.
6064 // Those take precedence over inherited constructors.
6065 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6066 // unless there is a user-declared constructor with the same signature in
6067 // the class where the using-declaration appears.
6068 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6069 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6070 CtorE = ClassDecl->ctor_end();
6071 CtorIt != CtorE; ++CtorIt) {
6072 ExistingConstructors.insert(
6073 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6074 }
6075
6076 Scope *S = getScopeForContext(ClassDecl);
6077 DeclarationName CreatedCtorName =
6078 Context.DeclarationNames.getCXXConstructorName(
6079 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6080
6081 // Now comes the true work.
6082 // First, we keep a map from constructor types to the base that introduced
6083 // them. Needed for finding conflicting constructors. We also keep the
6084 // actually inserted declarations in there, for pretty diagnostics.
6085 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6086 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6087 ConstructorToSourceMap InheritedConstructors;
6088 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6089 BaseE = BasesToInheritFrom.end();
6090 BaseIt != BaseE; ++BaseIt) {
6091 const RecordType *Base = *BaseIt;
6092 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6093 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6094 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6095 CtorE = BaseDecl->ctor_end();
6096 CtorIt != CtorE; ++CtorIt) {
6097 // Find the using declaration for inheriting this base's constructors.
6098 DeclarationName Name =
6099 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6100 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6101 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6102 SourceLocation UsingLoc = UD ? UD->getLocation() :
6103 ClassDecl->getLocation();
6104
6105 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6106 // from the class X named in the using-declaration consists of actual
6107 // constructors and notional constructors that result from the
6108 // transformation of defaulted parameters as follows:
6109 // - all non-template default constructors of X, and
6110 // - for each non-template constructor of X that has at least one
6111 // parameter with a default argument, the set of constructors that
6112 // results from omitting any ellipsis parameter specification and
6113 // successively omitting parameters with a default argument from the
6114 // end of the parameter-type-list.
6115 CXXConstructorDecl *BaseCtor = *CtorIt;
6116 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6117 const FunctionProtoType *BaseCtorType =
6118 BaseCtor->getType()->getAs<FunctionProtoType>();
6119
6120 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6121 maxParams = BaseCtor->getNumParams();
6122 params <= maxParams; ++params) {
6123 // Skip default constructors. They're never inherited.
6124 if (params == 0)
6125 continue;
6126 // Skip copy and move constructors for the same reason.
6127 if (CanBeCopyOrMove && params == 1)
6128 continue;
6129
6130 // Build up a function type for this particular constructor.
6131 // FIXME: The working paper does not consider that the exception spec
6132 // for the inheriting constructor might be larger than that of the
6133 // source. This code doesn't yet, either.
6134 const Type *NewCtorType;
6135 if (params == maxParams)
6136 NewCtorType = BaseCtorType;
6137 else {
6138 llvm::SmallVector<QualType, 16> Args;
6139 for (unsigned i = 0; i < params; ++i) {
6140 Args.push_back(BaseCtorType->getArgType(i));
6141 }
6142 FunctionProtoType::ExtProtoInfo ExtInfo =
6143 BaseCtorType->getExtProtoInfo();
6144 ExtInfo.Variadic = false;
6145 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6146 Args.data(), params, ExtInfo)
6147 .getTypePtr();
6148 }
6149 const Type *CanonicalNewCtorType =
6150 Context.getCanonicalType(NewCtorType);
6151
6152 // Now that we have the type, first check if the class already has a
6153 // constructor with this signature.
6154 if (ExistingConstructors.count(CanonicalNewCtorType))
6155 continue;
6156
6157 // Then we check if we have already declared an inherited constructor
6158 // with this signature.
6159 std::pair<ConstructorToSourceMap::iterator, bool> result =
6160 InheritedConstructors.insert(std::make_pair(
6161 CanonicalNewCtorType,
6162 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6163 if (!result.second) {
6164 // Already in the map. If it came from a different class, that's an
6165 // error. Not if it's from the same.
6166 CanQualType PreviousBase = result.first->second.first;
6167 if (CanonicalBase != PreviousBase) {
6168 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6169 const CXXConstructorDecl *PrevBaseCtor =
6170 PrevCtor->getInheritedConstructor();
6171 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6172
6173 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6174 Diag(BaseCtor->getLocation(),
6175 diag::note_using_decl_constructor_conflict_current_ctor);
6176 Diag(PrevBaseCtor->getLocation(),
6177 diag::note_using_decl_constructor_conflict_previous_ctor);
6178 Diag(PrevCtor->getLocation(),
6179 diag::note_using_decl_constructor_conflict_previous_using);
6180 }
6181 continue;
6182 }
6183
6184 // OK, we're there, now add the constructor.
6185 // C++0x [class.inhctor]p8: [...] that would be performed by a
6186 // user-writtern inline constructor [...]
6187 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6188 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006189 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6190 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006191 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00006192 NewCtor->setAccess(BaseCtor->getAccess());
6193
6194 // Build up the parameter decls and add them.
6195 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6196 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006197 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6198 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006199 /*IdentifierInfo=*/0,
6200 BaseCtorType->getArgType(i),
6201 /*TInfo=*/0, SC_None,
6202 SC_None, /*DefaultArg=*/0));
6203 }
6204 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6205 NewCtor->setInheritedConstructor(BaseCtor);
6206
6207 PushOnScopeChains(NewCtor, S, false);
6208 ClassDecl->addDecl(NewCtor);
6209 result.first->second.second = NewCtor;
6210 }
6211 }
6212 }
6213}
6214
Alexis Huntf91729462011-05-12 22:46:25 +00006215Sema::ImplicitExceptionSpecification
6216Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006217 // C++ [except.spec]p14:
6218 // An implicitly declared special member function (Clause 12) shall have
6219 // an exception-specification.
6220 ImplicitExceptionSpecification ExceptSpec(Context);
6221
6222 // Direct base-class destructors.
6223 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6224 BEnd = ClassDecl->bases_end();
6225 B != BEnd; ++B) {
6226 if (B->isVirtual()) // Handled below.
6227 continue;
6228
6229 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6230 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006231 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006232 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006233
Douglas Gregorf1203042010-07-01 19:09:28 +00006234 // Virtual base-class destructors.
6235 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6236 BEnd = ClassDecl->vbases_end();
6237 B != BEnd; ++B) {
6238 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6239 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006240 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006241 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006242
Douglas Gregorf1203042010-07-01 19:09:28 +00006243 // Field destructors.
6244 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6245 FEnd = ClassDecl->field_end();
6246 F != FEnd; ++F) {
6247 if (const RecordType *RecordTy
6248 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6249 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006250 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006251 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006252
Alexis Huntf91729462011-05-12 22:46:25 +00006253 return ExceptSpec;
6254}
6255
6256CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6257 // C++ [class.dtor]p2:
6258 // If a class has no user-declared destructor, a destructor is
6259 // declared implicitly. An implicitly-declared destructor is an
6260 // inline public member of its class.
6261
6262 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006263 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006264 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6265
Douglas Gregor7454c562010-07-02 20:37:36 +00006266 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006267 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006268
Douglas Gregorf1203042010-07-01 19:09:28 +00006269 CanQualType ClassType
6270 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006271 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006272 DeclarationName Name
6273 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006274 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006275 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006276 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6277 /*isInline=*/true,
6278 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006279 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006280 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006281 Destructor->setImplicit();
6282 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006283
6284 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006285 ++ASTContext::NumImplicitDestructorsDeclared;
6286
6287 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006288 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006289 PushOnScopeChains(Destructor, S, false);
6290 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006291
6292 // This could be uniqued if it ever proves significant.
6293 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006294
6295 if (ShouldDeleteDestructor(Destructor))
6296 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006297
6298 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006299
Douglas Gregorf1203042010-07-01 19:09:28 +00006300 return Destructor;
6301}
6302
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006303void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006304 CXXDestructorDecl *Destructor) {
Alexis Huntf91729462011-05-12 22:46:25 +00006305 assert((Destructor->isDefaulted() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006306 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006307 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006308 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006309
Douglas Gregor54818f02010-05-12 16:39:35 +00006310 if (Destructor->isInvalidDecl())
6311 return;
6312
Douglas Gregora57478e2010-05-01 15:04:51 +00006313 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006314
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006315 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006316 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6317 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006318
Douglas Gregor54818f02010-05-12 16:39:35 +00006319 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006320 Diag(CurrentLocation, diag::note_member_synthesized_at)
6321 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6322
6323 Destructor->setInvalidDecl();
6324 return;
6325 }
6326
Douglas Gregor73193272010-09-20 16:48:21 +00006327 SourceLocation Loc = Destructor->getLocation();
6328 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6329
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006330 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006331 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006332
6333 if (ASTMutationListener *L = getASTMutationListener()) {
6334 L->CompletedImplicitDefinition(Destructor);
6335 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006336}
6337
Sebastian Redl623ea822011-05-19 05:13:44 +00006338void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6339 CXXDestructorDecl *destructor) {
6340 // C++11 [class.dtor]p3:
6341 // A declaration of a destructor that does not have an exception-
6342 // specification is implicitly considered to have the same exception-
6343 // specification as an implicit declaration.
6344 const FunctionProtoType *dtorType = destructor->getType()->
6345 getAs<FunctionProtoType>();
6346 if (dtorType->hasExceptionSpec())
6347 return;
6348
6349 ImplicitExceptionSpecification exceptSpec =
6350 ComputeDefaultedDtorExceptionSpec(classDecl);
6351
6352 // Replace the destructor's type.
6353 FunctionProtoType::ExtProtoInfo epi;
6354 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6355 epi.NumExceptions = exceptSpec.size();
6356 epi.Exceptions = exceptSpec.data();
6357 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6358
6359 destructor->setType(ty);
6360
6361 // FIXME: If the destructor has a body that could throw, and the newly created
6362 // spec doesn't allow exceptions, we should emit a warning, because this
6363 // change in behavior can break conforming C++03 programs at runtime.
6364 // However, we don't have a body yet, so it needs to be done somewhere else.
6365}
6366
Douglas Gregorb139cd52010-05-01 20:49:11 +00006367/// \brief Builds a statement that copies the given entity from \p From to
6368/// \c To.
6369///
6370/// This routine is used to copy the members of a class with an
6371/// implicitly-declared copy assignment operator. When the entities being
6372/// copied are arrays, this routine builds for loops to copy them.
6373///
6374/// \param S The Sema object used for type-checking.
6375///
6376/// \param Loc The location where the implicit copy is being generated.
6377///
6378/// \param T The type of the expressions being copied. Both expressions must
6379/// have this type.
6380///
6381/// \param To The expression we are copying to.
6382///
6383/// \param From The expression we are copying from.
6384///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006385/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6386/// Otherwise, it's a non-static member subobject.
6387///
Douglas Gregorb139cd52010-05-01 20:49:11 +00006388/// \param Depth Internal parameter recording the depth of the recursion.
6389///
6390/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00006391static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00006392BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00006393 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006394 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006395 // C++0x [class.copy]p30:
6396 // Each subobject is assigned in the manner appropriate to its type:
6397 //
6398 // - if the subobject is of class type, the copy assignment operator
6399 // for the class is used (as if by explicit qualification; that is,
6400 // ignoring any possible virtual overriding functions in more derived
6401 // classes);
6402 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6403 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6404
6405 // Look for operator=.
6406 DeclarationName Name
6407 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6408 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6409 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6410
6411 // Filter out any result that isn't a copy-assignment operator.
6412 LookupResult::Filter F = OpLookup.makeFilter();
6413 while (F.hasNext()) {
6414 NamedDecl *D = F.next();
6415 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6416 if (Method->isCopyAssignmentOperator())
6417 continue;
6418
6419 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00006420 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006421 F.done();
6422
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006423 // Suppress the protected check (C++ [class.protected]) for each of the
6424 // assignment operators we found. This strange dance is required when
6425 // we're assigning via a base classes's copy-assignment operator. To
6426 // ensure that we're getting the right base class subobject (without
6427 // ambiguities), we need to cast "this" to that subobject type; to
6428 // ensure that we don't go through the virtual call mechanism, we need
6429 // to qualify the operator= name with the base class (see below). However,
6430 // this means that if the base class has a protected copy assignment
6431 // operator, the protected member access check will fail. So, we
6432 // rewrite "protected" access to "public" access in this case, since we
6433 // know by construction that we're calling from a derived class.
6434 if (CopyingBaseSubobject) {
6435 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6436 L != LEnd; ++L) {
6437 if (L.getAccess() == AS_protected)
6438 L.setAccess(AS_public);
6439 }
6440 }
6441
Douglas Gregorb139cd52010-05-01 20:49:11 +00006442 // Create the nested-name-specifier that will be used to qualify the
6443 // reference to operator=; this is required to suppress the virtual
6444 // call mechanism.
6445 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006446 SS.MakeTrivial(S.Context,
6447 NestedNameSpecifier::Create(S.Context, 0, false,
6448 T.getTypePtr()),
6449 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006450
6451 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00006452 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00006453 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006454 /*FirstQualifierInScope=*/0, OpLookup,
6455 /*TemplateArgs=*/0,
6456 /*SuppressQualifierCheck=*/true);
6457 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006458 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006459
6460 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00006461
John McCalldadc5752010-08-24 06:29:42 +00006462 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006463 OpEqualRef.takeAs<Expr>(),
6464 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006465 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006466 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006467
6468 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006469 }
John McCallab8c2732010-03-16 06:11:48 +00006470
Douglas Gregorb139cd52010-05-01 20:49:11 +00006471 // - if the subobject is of scalar type, the built-in assignment
6472 // operator is used.
6473 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6474 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00006475 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006476 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006477 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006478
6479 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006480 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006481
6482 // - if the subobject is an array, each element is assigned, in the
6483 // manner appropriate to the element type;
6484
6485 // Construct a loop over the array bounds, e.g.,
6486 //
6487 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6488 //
6489 // that will copy each of the array elements.
6490 QualType SizeType = S.Context.getSizeType();
6491
6492 // Create the iteration variable.
6493 IdentifierInfo *IterationVarName = 0;
6494 {
6495 llvm::SmallString<8> Str;
6496 llvm::raw_svector_ostream OS(Str);
6497 OS << "__i" << Depth;
6498 IterationVarName = &S.Context.Idents.get(OS.str());
6499 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00006500 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006501 IterationVarName, SizeType,
6502 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006503 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006504
6505 // Initialize the iteration variable to zero.
6506 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006507 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006508
6509 // Create a reference to the iteration variable; we'll use this several
6510 // times throughout.
6511 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00006512 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006513 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6514
6515 // Create the DeclStmt that holds the iteration variable.
6516 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6517
6518 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006519 llvm::APInt Upper
6520 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00006521 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00006522 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00006523 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6524 BO_NE, S.Context.BoolTy,
6525 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006526
6527 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006528 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00006529 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6530 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006531
6532 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006533 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6534 IterationVarRef, Loc));
6535 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6536 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006537
6538 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00006539 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6540 To, From, CopyingBaseSubobject,
6541 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00006542 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006543 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006544
6545 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00006546 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006547 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00006548 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00006549 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006550}
6551
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006552/// \brief Determine whether the given class has a copy assignment operator
6553/// that accepts a const-qualified argument.
6554static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6555 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6556
6557 if (!Class->hasDeclaredCopyAssignment())
6558 S.DeclareImplicitCopyAssignment(Class);
6559
6560 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6561 DeclarationName OpName
6562 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6563
6564 DeclContext::lookup_const_iterator Op, OpEnd;
6565 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6566 // C++ [class.copy]p9:
6567 // A user-declared copy assignment operator is a non-static non-template
6568 // member function of class X with exactly one parameter of type X, X&,
6569 // const X&, volatile X& or const volatile X&.
6570 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6571 if (!Method)
6572 continue;
6573
6574 if (Method->isStatic())
6575 continue;
6576 if (Method->getPrimaryTemplate())
6577 continue;
6578 const FunctionProtoType *FnType =
6579 Method->getType()->getAs<FunctionProtoType>();
6580 assert(FnType && "Overloaded operator has no prototype.");
6581 // Don't assert on this; an invalid decl might have been left in the AST.
6582 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6583 continue;
6584 bool AcceptsConst = true;
6585 QualType ArgType = FnType->getArgType(0);
6586 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6587 ArgType = Ref->getPointeeType();
6588 // Is it a non-const lvalue reference?
6589 if (!ArgType.isConstQualified())
6590 AcceptsConst = false;
6591 }
6592 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6593 continue;
6594
6595 // We have a single argument of type cv X or cv X&, i.e. we've found the
6596 // copy assignment operator. Return whether it accepts const arguments.
6597 return AcceptsConst;
6598 }
6599 assert(Class->isInvalidDecl() &&
6600 "No copy assignment operator declared in valid code.");
6601 return false;
6602}
6603
Alexis Hunt119f3652011-05-14 05:23:20 +00006604std::pair<Sema::ImplicitExceptionSpecification, bool>
6605Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6606 CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006607 // C++ [class.copy]p10:
6608 // If the class definition does not explicitly declare a copy
6609 // assignment operator, one is declared implicitly.
6610 // The implicitly-defined copy assignment operator for a class X
6611 // will have the form
6612 //
6613 // X& X::operator=(const X&)
6614 //
6615 // if
6616 bool HasConstCopyAssignment = true;
6617
6618 // -- each direct base class B of X has a copy assignment operator
6619 // whose parameter is of type const B&, const volatile B& or B,
6620 // and
6621 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6622 BaseEnd = ClassDecl->bases_end();
6623 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6624 assert(!Base->getType()->isDependentType() &&
6625 "Cannot generate implicit members for class with dependent bases.");
6626 const CXXRecordDecl *BaseClassDecl
6627 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006628 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006629 }
6630
6631 // -- for all the nonstatic data members of X that are of a class
6632 // type M (or array thereof), each such class type has a copy
6633 // assignment operator whose parameter is of type const M&,
6634 // const volatile M& or M.
6635 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6636 FieldEnd = ClassDecl->field_end();
6637 HasConstCopyAssignment && Field != FieldEnd;
6638 ++Field) {
6639 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6640 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6641 const CXXRecordDecl *FieldClassDecl
6642 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006643 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006644 }
6645 }
6646
6647 // Otherwise, the implicitly declared copy assignment operator will
6648 // have the form
6649 //
6650 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006651
Douglas Gregor68e11362010-07-01 17:48:08 +00006652 // C++ [except.spec]p14:
6653 // An implicitly declared special member function (Clause 12) shall have an
6654 // exception-specification. [...]
6655 ImplicitExceptionSpecification ExceptSpec(Context);
6656 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6657 BaseEnd = ClassDecl->bases_end();
6658 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006659 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006660 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006661
6662 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6663 DeclareImplicitCopyAssignment(BaseClassDecl);
6664
Douglas Gregor68e11362010-07-01 17:48:08 +00006665 if (CXXMethodDecl *CopyAssign
6666 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6667 ExceptSpec.CalledDecl(CopyAssign);
6668 }
6669 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6670 FieldEnd = ClassDecl->field_end();
6671 Field != FieldEnd;
6672 ++Field) {
6673 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6674 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006675 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006676 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006677
6678 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6679 DeclareImplicitCopyAssignment(FieldClassDecl);
6680
Douglas Gregor68e11362010-07-01 17:48:08 +00006681 if (CXXMethodDecl *CopyAssign
6682 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6683 ExceptSpec.CalledDecl(CopyAssign);
6684 }
6685 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006686
Alexis Hunt119f3652011-05-14 05:23:20 +00006687 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6688}
6689
6690CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6691 // Note: The following rules are largely analoguous to the copy
6692 // constructor rules. Note that virtual bases are not taken into account
6693 // for determining the argument type of the operator. Note also that
6694 // operators taking an object instead of a reference are allowed.
6695
6696 ImplicitExceptionSpecification Spec(Context);
6697 bool Const;
6698 llvm::tie(Spec, Const) =
6699 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6700
6701 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6702 QualType RetType = Context.getLValueReferenceType(ArgType);
6703 if (Const)
6704 ArgType = ArgType.withConst();
6705 ArgType = Context.getLValueReferenceType(ArgType);
6706
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006707 // An implicitly-declared copy assignment operator is an inline public
6708 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00006709 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006710 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006711 SourceLocation ClassLoc = ClassDecl->getLocation();
6712 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006713 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00006714 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00006715 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006716 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00006717 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00006718 /*isInline=*/true,
6719 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006720 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00006721 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006722 CopyAssignment->setImplicit();
6723 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006724
6725 // Add the parameter to the operator.
6726 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006727 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006728 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006729 SC_None,
6730 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006731 CopyAssignment->setParams(&FromParam, 1);
6732
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006733 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006734 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00006735
Douglas Gregor0be31a22010-07-02 17:43:08 +00006736 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006737 PushOnScopeChains(CopyAssignment, S, false);
6738 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006739
Alexis Hunte77a28f2011-05-18 03:41:58 +00006740 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6741 CopyAssignment->setDeletedAsWritten();
6742
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006743 AddOverriddenMethods(ClassDecl, CopyAssignment);
6744 return CopyAssignment;
6745}
6746
Douglas Gregorb139cd52010-05-01 20:49:11 +00006747void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6748 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00006749 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006750 CopyAssignOperator->isOverloadedOperator() &&
6751 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00006752 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006753 "DefineImplicitCopyAssignment called for wrong function");
6754
6755 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6756
6757 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6758 CopyAssignOperator->setInvalidDecl();
6759 return;
6760 }
6761
6762 CopyAssignOperator->setUsed();
6763
6764 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006765 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006766
6767 // C++0x [class.copy]p30:
6768 // The implicitly-defined or explicitly-defaulted copy assignment operator
6769 // for a non-union class X performs memberwise copy assignment of its
6770 // subobjects. The direct base classes of X are assigned first, in the
6771 // order of their declaration in the base-specifier-list, and then the
6772 // immediate non-static data members of X are assigned, in the order in
6773 // which they were declared in the class definition.
6774
6775 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00006776 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006777
6778 // The parameter for the "other" object, which we are copying from.
6779 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6780 Qualifiers OtherQuals = Other->getType().getQualifiers();
6781 QualType OtherRefType = Other->getType();
6782 if (const LValueReferenceType *OtherRef
6783 = OtherRefType->getAs<LValueReferenceType>()) {
6784 OtherRefType = OtherRef->getPointeeType();
6785 OtherQuals = OtherRefType.getQualifiers();
6786 }
6787
6788 // Our location for everything implicitly-generated.
6789 SourceLocation Loc = CopyAssignOperator->getLocation();
6790
6791 // Construct a reference to the "other" object. We'll be using this
6792 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00006793 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006794 assert(OtherRef && "Reference to parameter cannot fail!");
6795
6796 // Construct the "this" pointer. We'll be using this throughout the generated
6797 // ASTs.
6798 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6799 assert(This && "Reference to this cannot fail!");
6800
6801 // Assign base classes.
6802 bool Invalid = false;
6803 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6804 E = ClassDecl->bases_end(); Base != E; ++Base) {
6805 // Form the assignment:
6806 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6807 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00006808 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006809 Invalid = true;
6810 continue;
6811 }
6812
John McCallcf142162010-08-07 06:22:56 +00006813 CXXCastPath BasePath;
6814 BasePath.push_back(Base);
6815
Douglas Gregorb139cd52010-05-01 20:49:11 +00006816 // Construct the "from" expression, which is an implicit cast to the
6817 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00006818 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00006819 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6820 CK_UncheckedDerivedToBase,
6821 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006822
6823 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00006824 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006825
6826 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00006827 To = ImpCastExprToType(To.take(),
6828 Context.getCVRQualifiedType(BaseType,
6829 CopyAssignOperator->getTypeQualifiers()),
6830 CK_UncheckedDerivedToBase,
6831 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006832
6833 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00006834 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00006835 To.get(), From,
6836 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006837 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006838 Diag(CurrentLocation, diag::note_member_synthesized_at)
6839 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6840 CopyAssignOperator->setInvalidDecl();
6841 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006842 }
6843
6844 // Success! Record the copy.
6845 Statements.push_back(Copy.takeAs<Expr>());
6846 }
6847
6848 // \brief Reference to the __builtin_memcpy function.
6849 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006850 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006851 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006852
6853 // Assign non-static members.
6854 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6855 FieldEnd = ClassDecl->field_end();
6856 Field != FieldEnd; ++Field) {
6857 // Check for members of reference type; we can't copy those.
6858 if (Field->getType()->isReferenceType()) {
6859 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6860 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6861 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006862 Diag(CurrentLocation, diag::note_member_synthesized_at)
6863 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006864 Invalid = true;
6865 continue;
6866 }
6867
6868 // Check for members of const-qualified, non-class type.
6869 QualType BaseType = Context.getBaseElementType(Field->getType());
6870 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6871 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6872 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6873 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006874 Diag(CurrentLocation, diag::note_member_synthesized_at)
6875 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006876 Invalid = true;
6877 continue;
6878 }
6879
6880 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00006881 if (FieldType->isIncompleteArrayType()) {
6882 assert(ClassDecl->hasFlexibleArrayMember() &&
6883 "Incomplete array type is not valid");
6884 continue;
6885 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006886
6887 // Build references to the field in the object we're copying from and to.
6888 CXXScopeSpec SS; // Intentionally empty
6889 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6890 LookupMemberName);
6891 MemberLookup.addDecl(*Field);
6892 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00006893 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00006894 Loc, /*IsArrow=*/false,
6895 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00006896 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00006897 Loc, /*IsArrow=*/true,
6898 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006899 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6900 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6901
6902 // If the field should be copied with __builtin_memcpy rather than via
6903 // explicit assignments, do so. This optimization only applies for arrays
6904 // of scalars and arrays of class type with trivial copy-assignment
6905 // operators.
6906 if (FieldType->isArrayType() &&
6907 (!BaseType->isRecordType() ||
6908 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
6909 ->hasTrivialCopyAssignment())) {
6910 // Compute the size of the memory buffer to be copied.
6911 QualType SizeType = Context.getSizeType();
6912 llvm::APInt Size(Context.getTypeSize(SizeType),
6913 Context.getTypeSizeInChars(BaseType).getQuantity());
6914 for (const ConstantArrayType *Array
6915 = Context.getAsConstantArrayType(FieldType);
6916 Array;
6917 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00006918 llvm::APInt ArraySize
6919 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006920 Size *= ArraySize;
6921 }
6922
6923 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00006924 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6925 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006926
6927 bool NeedsCollectableMemCpy =
6928 (BaseType->isRecordType() &&
6929 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6930
6931 if (NeedsCollectableMemCpy) {
6932 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006933 // Create a reference to the __builtin_objc_memmove_collectable function.
6934 LookupResult R(*this,
6935 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006936 Loc, LookupOrdinaryName);
6937 LookupName(R, TUScope, true);
6938
6939 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6940 if (!CollectableMemCpy) {
6941 // Something went horribly wrong earlier, and we will have
6942 // complained about it.
6943 Invalid = true;
6944 continue;
6945 }
6946
6947 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6948 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006949 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006950 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6951 }
6952 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006953 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006954 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006955 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6956 LookupOrdinaryName);
6957 LookupName(R, TUScope, true);
6958
6959 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6960 if (!BuiltinMemCpy) {
6961 // Something went horribly wrong earlier, and we will have complained
6962 // about it.
6963 Invalid = true;
6964 continue;
6965 }
6966
6967 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6968 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006969 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006970 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6971 }
6972
John McCall37ad5512010-08-23 06:44:23 +00006973 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006974 CallArgs.push_back(To.takeAs<Expr>());
6975 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006976 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00006977 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006978 if (NeedsCollectableMemCpy)
6979 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006980 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006981 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006982 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006983 else
6984 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006985 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006986 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006987 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006988
Douglas Gregorb139cd52010-05-01 20:49:11 +00006989 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
6990 Statements.push_back(Call.takeAs<Expr>());
6991 continue;
6992 }
6993
6994 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00006995 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00006996 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006997 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006998 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006999 Diag(CurrentLocation, diag::note_member_synthesized_at)
7000 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7001 CopyAssignOperator->setInvalidDecl();
7002 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007003 }
7004
7005 // Success! Record the copy.
7006 Statements.push_back(Copy.takeAs<Stmt>());
7007 }
7008
7009 if (!Invalid) {
7010 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007011 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007012
John McCalldadc5752010-08-24 06:29:42 +00007013 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007014 if (Return.isInvalid())
7015 Invalid = true;
7016 else {
7017 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007018
7019 if (Trap.hasErrorOccurred()) {
7020 Diag(CurrentLocation, diag::note_member_synthesized_at)
7021 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7022 Invalid = true;
7023 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007024 }
7025 }
7026
7027 if (Invalid) {
7028 CopyAssignOperator->setInvalidDecl();
7029 return;
7030 }
7031
John McCalldadc5752010-08-24 06:29:42 +00007032 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007033 /*isStmtExpr=*/false);
7034 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7035 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007036
7037 if (ASTMutationListener *L = getASTMutationListener()) {
7038 L->CompletedImplicitDefinition(CopyAssignOperator);
7039 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007040}
7041
Alexis Hunt913820d2011-05-13 06:10:58 +00007042std::pair<Sema::ImplicitExceptionSpecification, bool>
7043Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00007044 // C++ [class.copy]p5:
7045 // The implicitly-declared copy constructor for a class X will
7046 // have the form
7047 //
7048 // X::X(const X&)
7049 //
7050 // if
7051 bool HasConstCopyConstructor = true;
7052
7053 // -- each direct or virtual base class B of X has a copy
7054 // constructor whose first parameter is of type const B& or
7055 // const volatile B&, and
7056 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7057 BaseEnd = ClassDecl->bases_end();
7058 HasConstCopyConstructor && Base != BaseEnd;
7059 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007060 // Virtual bases are handled below.
7061 if (Base->isVirtual())
7062 continue;
7063
Douglas Gregora6d69502010-07-02 23:41:54 +00007064 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007065 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007066 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7067 DeclareImplicitCopyConstructor(BaseClassDecl);
7068
Douglas Gregorcfe68222010-07-01 18:27:03 +00007069 HasConstCopyConstructor
7070 = BaseClassDecl->hasConstCopyConstructor(Context);
7071 }
7072
7073 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7074 BaseEnd = ClassDecl->vbases_end();
7075 HasConstCopyConstructor && Base != BaseEnd;
7076 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007077 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00007078 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007079 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7080 DeclareImplicitCopyConstructor(BaseClassDecl);
7081
Douglas Gregor54be3392010-07-01 17:57:27 +00007082 HasConstCopyConstructor
7083 = BaseClassDecl->hasConstCopyConstructor(Context);
7084 }
7085
7086 // -- for all the nonstatic data members of X that are of a
7087 // class type M (or array thereof), each such class type
7088 // has a copy constructor whose first parameter is of type
7089 // const M& or const volatile M&.
7090 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7091 FieldEnd = ClassDecl->field_end();
7092 HasConstCopyConstructor && Field != FieldEnd;
7093 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007094 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00007095 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007096 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007097 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007098 if (!FieldClassDecl->hasDeclaredCopyConstructor())
7099 DeclareImplicitCopyConstructor(FieldClassDecl);
7100
Douglas Gregor54be3392010-07-01 17:57:27 +00007101 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00007102 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00007103 }
7104 }
Douglas Gregor54be3392010-07-01 17:57:27 +00007105 // Otherwise, the implicitly declared copy constructor will have
7106 // the form
7107 //
7108 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00007109
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007110 // C++ [except.spec]p14:
7111 // An implicitly declared special member function (Clause 12) shall have an
7112 // exception-specification. [...]
7113 ImplicitExceptionSpecification ExceptSpec(Context);
7114 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7115 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7116 BaseEnd = ClassDecl->bases_end();
7117 Base != BaseEnd;
7118 ++Base) {
7119 // Virtual bases are handled below.
7120 if (Base->isVirtual())
7121 continue;
7122
Douglas Gregora6d69502010-07-02 23:41:54 +00007123 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007124 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007125 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7126 DeclareImplicitCopyConstructor(BaseClassDecl);
7127
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007128 if (CXXConstructorDecl *CopyConstructor
7129 = BaseClassDecl->getCopyConstructor(Context, Quals))
7130 ExceptSpec.CalledDecl(CopyConstructor);
7131 }
7132 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7133 BaseEnd = ClassDecl->vbases_end();
7134 Base != BaseEnd;
7135 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007136 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007137 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007138 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7139 DeclareImplicitCopyConstructor(BaseClassDecl);
7140
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007141 if (CXXConstructorDecl *CopyConstructor
7142 = BaseClassDecl->getCopyConstructor(Context, Quals))
7143 ExceptSpec.CalledDecl(CopyConstructor);
7144 }
7145 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7146 FieldEnd = ClassDecl->field_end();
7147 Field != FieldEnd;
7148 ++Field) {
7149 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7150 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007151 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007152 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007153 if (!FieldClassDecl->hasDeclaredCopyConstructor())
7154 DeclareImplicitCopyConstructor(FieldClassDecl);
7155
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007156 if (CXXConstructorDecl *CopyConstructor
7157 = FieldClassDecl->getCopyConstructor(Context, Quals))
7158 ExceptSpec.CalledDecl(CopyConstructor);
7159 }
7160 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007161
Alexis Hunt913820d2011-05-13 06:10:58 +00007162 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7163}
7164
7165CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7166 CXXRecordDecl *ClassDecl) {
7167 // C++ [class.copy]p4:
7168 // If the class definition does not explicitly declare a copy
7169 // constructor, one is declared implicitly.
7170
7171 ImplicitExceptionSpecification Spec(Context);
7172 bool Const;
7173 llvm::tie(Spec, Const) =
7174 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7175
7176 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7177 QualType ArgType = ClassType;
7178 if (Const)
7179 ArgType = ArgType.withConst();
7180 ArgType = Context.getLValueReferenceType(ArgType);
7181
7182 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7183
Douglas Gregor54be3392010-07-01 17:57:27 +00007184 DeclarationName Name
7185 = Context.DeclarationNames.getCXXConstructorName(
7186 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007187 SourceLocation ClassLoc = ClassDecl->getLocation();
7188 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00007189
7190 // An implicitly-declared copy constructor is an inline public
7191 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00007192 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00007193 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00007194 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00007195 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00007196 /*TInfo=*/0,
7197 /*isExplicit=*/false,
7198 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00007199 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00007200 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00007201 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00007202 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7203
Douglas Gregora6d69502010-07-02 23:41:54 +00007204 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00007205 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7206
Douglas Gregor54be3392010-07-01 17:57:27 +00007207 // Add the parameter to the constructor.
7208 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007209 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00007210 /*IdentifierInfo=*/0,
7211 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007212 SC_None,
7213 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00007214 CopyConstructor->setParams(&FromParam, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00007215
Douglas Gregor0be31a22010-07-02 17:43:08 +00007216 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00007217 PushOnScopeChains(CopyConstructor, S, false);
7218 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007219
7220 if (ShouldDeleteCopyConstructor(CopyConstructor))
7221 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00007222
7223 return CopyConstructor;
7224}
7225
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007226void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00007227 CXXConstructorDecl *CopyConstructor) {
7228 assert((CopyConstructor->isDefaulted() &&
7229 CopyConstructor->isCopyConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00007230 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007231 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007232
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00007233 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007234 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007235
Douglas Gregora57478e2010-05-01 15:04:51 +00007236 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007237 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007238
Alexis Hunt1d792652011-01-08 20:30:50 +00007239 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007240 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00007241 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00007242 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00007243 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00007244 } else {
7245 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7246 CopyConstructor->getLocation(),
7247 MultiStmtArg(*this, 0, 0),
7248 /*isStmtExpr=*/false)
7249 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00007250 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00007251
7252 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00007253
7254 if (ASTMutationListener *L = getASTMutationListener()) {
7255 L->CompletedImplicitDefinition(CopyConstructor);
7256 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007257}
7258
John McCalldadc5752010-08-24 06:29:42 +00007259ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007260Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00007261 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007262 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007263 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007264 unsigned ConstructKind,
7265 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00007266 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00007267
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007268 // C++0x [class.copy]p34:
7269 // When certain criteria are met, an implementation is allowed to
7270 // omit the copy/move construction of a class object, even if the
7271 // copy/move constructor and/or destructor for the object have
7272 // side effects. [...]
7273 // - when a temporary class object that has not been bound to a
7274 // reference (12.2) would be copied/moved to a class object
7275 // with the same cv-unqualified type, the copy/move operation
7276 // can be omitted by constructing the temporary object
7277 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00007278 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00007279 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007280 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00007281 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00007282 }
Mike Stump11289f42009-09-09 15:08:12 +00007283
7284 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007285 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007286 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00007287}
7288
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007289/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7290/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00007291ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007292Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7293 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007294 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007295 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007296 unsigned ConstructKind,
7297 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007298 unsigned NumExprs = ExprArgs.size();
7299 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00007300
Nick Lewyckyd4693212011-03-25 01:44:32 +00007301 for (specific_attr_iterator<NonNullAttr>
7302 i = Constructor->specific_attr_begin<NonNullAttr>(),
7303 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7304 const NonNullAttr *NonNull = *i;
7305 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7306 }
7307
Douglas Gregor27381f32009-11-23 12:27:39 +00007308 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00007309 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007310 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00007311 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007312 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7313 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007314}
7315
Mike Stump11289f42009-09-09 15:08:12 +00007316bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007317 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007318 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00007319 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00007320 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00007321 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00007322 move(Exprs), false, CXXConstructExpr::CK_Complete,
7323 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007324 if (TempResult.isInvalid())
7325 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007326
Anders Carlsson6eb55572009-08-25 05:12:04 +00007327 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00007328 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00007329 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00007330 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00007331 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00007332
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007333 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00007334}
7335
John McCall03c48482010-02-02 09:10:11 +00007336void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00007337 if (VD->isInvalidDecl()) return;
7338
John McCall03c48482010-02-02 09:10:11 +00007339 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00007340 if (ClassDecl->isInvalidDecl()) return;
7341 if (ClassDecl->hasTrivialDestructor()) return;
7342 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00007343
Chandler Carruth86d17d32011-03-27 21:26:48 +00007344 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7345 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7346 CheckDestructorAccess(VD->getLocation(), Destructor,
7347 PDiag(diag::err_access_dtor_var)
7348 << VD->getDeclName()
7349 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00007350
Chandler Carruth86d17d32011-03-27 21:26:48 +00007351 if (!VD->hasGlobalStorage()) return;
7352
7353 // Emit warning for non-trivial dtor in global scope (a real global,
7354 // class-static, function-static).
7355 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7356
7357 // TODO: this should be re-enabled for static locals by !CXAAtExit
7358 if (!VD->isStaticLocal())
7359 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007360}
7361
Mike Stump11289f42009-09-09 15:08:12 +00007362/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007363/// ActOnDeclarator, when a C++ direct initializer is present.
7364/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00007365void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007366 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007367 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00007368 SourceLocation RParenLoc,
7369 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00007370 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007371
7372 // If there is no declaration, there was an error parsing it. Just ignore
7373 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00007374 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007375 return;
Mike Stump11289f42009-09-09 15:08:12 +00007376
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007377 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7378 if (!VDecl) {
7379 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7380 RealDecl->setInvalidDecl();
7381 return;
7382 }
7383
Richard Smith30482bc2011-02-20 03:19:35 +00007384 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7385 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00007386 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7387 if (Exprs.size() > 1) {
7388 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7389 diag::err_auto_var_init_multiple_expressions)
7390 << VDecl->getDeclName() << VDecl->getType()
7391 << VDecl->getSourceRange();
7392 RealDecl->setInvalidDecl();
7393 return;
7394 }
7395
7396 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00007397 TypeSourceInfo *DeducedType = 0;
7398 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00007399 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7400 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7401 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00007402 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00007403 RealDecl->setInvalidDecl();
7404 return;
7405 }
Richard Smith9647d3c2011-03-17 16:11:59 +00007406 VDecl->setTypeSourceInfo(DeducedType);
7407 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00007408
7409 // If this is a redeclaration, check that the type we just deduced matches
7410 // the previously declared type.
7411 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7412 MergeVarDeclTypes(VDecl, Old);
7413 }
7414
Douglas Gregor402250f2009-08-26 21:14:46 +00007415 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007416 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007417 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7418 //
7419 // Clients that want to distinguish between the two forms, can check for
7420 // direct initializer using VarDecl::hasCXXDirectInitializer().
7421 // A major benefit is that clients that don't particularly care about which
7422 // exactly form was it (like the CodeGen) can handle both cases without
7423 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007424
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007425 // C++ 8.5p11:
7426 // The form of initialization (using parentheses or '=') is generally
7427 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007428 // class type.
7429
Douglas Gregor50dc2192010-02-11 22:55:30 +00007430 if (!VDecl->getType()->isDependentType() &&
7431 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00007432 diag::err_typecheck_decl_incomplete_type)) {
7433 VDecl->setInvalidDecl();
7434 return;
7435 }
7436
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007437 // The variable can not have an abstract class type.
7438 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7439 diag::err_abstract_type_in_decl,
7440 AbstractVariableType))
7441 VDecl->setInvalidDecl();
7442
Sebastian Redl5ca79842010-02-01 20:16:42 +00007443 const VarDecl *Def;
7444 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007445 Diag(VDecl->getLocation(), diag::err_redefinition)
7446 << VDecl->getDeclName();
7447 Diag(Def->getLocation(), diag::note_previous_definition);
7448 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007449 return;
7450 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00007451
Douglas Gregorf0f83692010-08-24 05:27:49 +00007452 // C++ [class.static.data]p4
7453 // If a static data member is of const integral or const
7454 // enumeration type, its declaration in the class definition can
7455 // specify a constant-initializer which shall be an integral
7456 // constant expression (5.19). In that case, the member can appear
7457 // in integral constant expressions. The member shall still be
7458 // defined in a namespace scope if it is used in the program and the
7459 // namespace scope definition shall not contain an initializer.
7460 //
7461 // We already performed a redefinition check above, but for static
7462 // data members we also need to check whether there was an in-class
7463 // declaration with an initializer.
7464 const VarDecl* PrevInit = 0;
7465 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7466 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7467 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7468 return;
7469 }
7470
Douglas Gregor71f39c92010-12-16 01:31:22 +00007471 bool IsDependent = false;
7472 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7473 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7474 VDecl->setInvalidDecl();
7475 return;
7476 }
7477
7478 if (Exprs.get()[I]->isTypeDependent())
7479 IsDependent = true;
7480 }
7481
Douglas Gregor50dc2192010-02-11 22:55:30 +00007482 // If either the declaration has a dependent type or if any of the
7483 // expressions is type-dependent, we represent the initialization
7484 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00007485 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00007486 // Let clients know that initialization was done with a direct initializer.
7487 VDecl->setCXXDirectInitializer(true);
7488
7489 // Store the initialization expressions as a ParenListExpr.
7490 unsigned NumExprs = Exprs.size();
7491 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7492 (Expr **)Exprs.release(),
7493 NumExprs, RParenLoc));
7494 return;
7495 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007496
7497 // Capture the variable that is being initialized and the style of
7498 // initialization.
7499 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7500
7501 // FIXME: Poor source location information.
7502 InitializationKind Kind
7503 = InitializationKind::CreateDirect(VDecl->getLocation(),
7504 LParenLoc, RParenLoc);
7505
7506 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00007507 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00007508 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007509 if (Result.isInvalid()) {
7510 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007511 return;
7512 }
John McCallacf0ee52010-10-08 02:01:28 +00007513
7514 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007515
Douglas Gregora40433a2010-12-07 00:41:46 +00007516 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00007517 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007518 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007519
John McCall8b7fd8f12011-01-19 11:48:09 +00007520 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007521}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007522
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007523/// \brief Given a constructor and the set of arguments provided for the
7524/// constructor, convert the arguments and add any required default arguments
7525/// to form a proper call to this constructor.
7526///
7527/// \returns true if an error occurred, false otherwise.
7528bool
7529Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7530 MultiExprArg ArgsPtr,
7531 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00007532 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007533 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7534 unsigned NumArgs = ArgsPtr.size();
7535 Expr **Args = (Expr **)ArgsPtr.get();
7536
7537 const FunctionProtoType *Proto
7538 = Constructor->getType()->getAs<FunctionProtoType>();
7539 assert(Proto && "Constructor without a prototype?");
7540 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007541
7542 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007543 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007544 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007545 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007546 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007547
7548 VariadicCallType CallType =
7549 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7550 llvm::SmallVector<Expr *, 8> AllArgs;
7551 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7552 Proto, 0, Args, NumArgs, AllArgs,
7553 CallType);
7554 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7555 ConvertedArgs.push_back(AllArgs[i]);
7556 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00007557}
7558
Anders Carlssone363c8e2009-12-12 00:32:00 +00007559static inline bool
7560CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7561 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007562 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00007563 if (isa<NamespaceDecl>(DC)) {
7564 return SemaRef.Diag(FnDecl->getLocation(),
7565 diag::err_operator_new_delete_declared_in_namespace)
7566 << FnDecl->getDeclName();
7567 }
7568
7569 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00007570 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007571 return SemaRef.Diag(FnDecl->getLocation(),
7572 diag::err_operator_new_delete_declared_static)
7573 << FnDecl->getDeclName();
7574 }
7575
Anders Carlsson60659a82009-12-12 02:43:16 +00007576 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00007577}
7578
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007579static inline bool
7580CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7581 CanQualType ExpectedResultType,
7582 CanQualType ExpectedFirstParamType,
7583 unsigned DependentParamTypeDiag,
7584 unsigned InvalidParamTypeDiag) {
7585 QualType ResultType =
7586 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7587
7588 // Check that the result type is not dependent.
7589 if (ResultType->isDependentType())
7590 return SemaRef.Diag(FnDecl->getLocation(),
7591 diag::err_operator_new_delete_dependent_result_type)
7592 << FnDecl->getDeclName() << ExpectedResultType;
7593
7594 // Check that the result type is what we expect.
7595 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7596 return SemaRef.Diag(FnDecl->getLocation(),
7597 diag::err_operator_new_delete_invalid_result_type)
7598 << FnDecl->getDeclName() << ExpectedResultType;
7599
7600 // A function template must have at least 2 parameters.
7601 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7602 return SemaRef.Diag(FnDecl->getLocation(),
7603 diag::err_operator_new_delete_template_too_few_parameters)
7604 << FnDecl->getDeclName();
7605
7606 // The function decl must have at least 1 parameter.
7607 if (FnDecl->getNumParams() == 0)
7608 return SemaRef.Diag(FnDecl->getLocation(),
7609 diag::err_operator_new_delete_too_few_parameters)
7610 << FnDecl->getDeclName();
7611
7612 // Check the the first parameter type is not dependent.
7613 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7614 if (FirstParamType->isDependentType())
7615 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7616 << FnDecl->getDeclName() << ExpectedFirstParamType;
7617
7618 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00007619 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007620 ExpectedFirstParamType)
7621 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7622 << FnDecl->getDeclName() << ExpectedFirstParamType;
7623
7624 return false;
7625}
7626
Anders Carlsson12308f42009-12-11 23:23:22 +00007627static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007628CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007629 // C++ [basic.stc.dynamic.allocation]p1:
7630 // A program is ill-formed if an allocation function is declared in a
7631 // namespace scope other than global scope or declared static in global
7632 // scope.
7633 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7634 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007635
7636 CanQualType SizeTy =
7637 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7638
7639 // C++ [basic.stc.dynamic.allocation]p1:
7640 // The return type shall be void*. The first parameter shall have type
7641 // std::size_t.
7642 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7643 SizeTy,
7644 diag::err_operator_new_dependent_param_type,
7645 diag::err_operator_new_param_type))
7646 return true;
7647
7648 // C++ [basic.stc.dynamic.allocation]p1:
7649 // The first parameter shall not have an associated default argument.
7650 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00007651 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007652 diag::err_operator_new_default_arg)
7653 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7654
7655 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00007656}
7657
7658static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00007659CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7660 // C++ [basic.stc.dynamic.deallocation]p1:
7661 // A program is ill-formed if deallocation functions are declared in a
7662 // namespace scope other than global scope or declared static in global
7663 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00007664 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7665 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007666
7667 // C++ [basic.stc.dynamic.deallocation]p2:
7668 // Each deallocation function shall return void and its first parameter
7669 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007670 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7671 SemaRef.Context.VoidPtrTy,
7672 diag::err_operator_delete_dependent_param_type,
7673 diag::err_operator_delete_param_type))
7674 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007675
Anders Carlsson12308f42009-12-11 23:23:22 +00007676 return false;
7677}
7678
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007679/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7680/// of this overloaded operator is well-formed. If so, returns false;
7681/// otherwise, emits appropriate diagnostics and returns true.
7682bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00007683 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007684 "Expected an overloaded operator declaration");
7685
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007686 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7687
Mike Stump11289f42009-09-09 15:08:12 +00007688 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007689 // The allocation and deallocation functions, operator new,
7690 // operator new[], operator delete and operator delete[], are
7691 // described completely in 3.7.3. The attributes and restrictions
7692 // found in the rest of this subclause do not apply to them unless
7693 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00007694 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00007695 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00007696
Anders Carlsson22f443f2009-12-12 00:26:23 +00007697 if (Op == OO_New || Op == OO_Array_New)
7698 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007699
7700 // C++ [over.oper]p6:
7701 // An operator function shall either be a non-static member
7702 // function or be a non-member function and have at least one
7703 // parameter whose type is a class, a reference to a class, an
7704 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00007705 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7706 if (MethodDecl->isStatic())
7707 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007708 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007709 } else {
7710 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00007711 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7712 ParamEnd = FnDecl->param_end();
7713 Param != ParamEnd; ++Param) {
7714 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00007715 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7716 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007717 ClassOrEnumParam = true;
7718 break;
7719 }
7720 }
7721
Douglas Gregord69246b2008-11-17 16:14:12 +00007722 if (!ClassOrEnumParam)
7723 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007724 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007725 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007726 }
7727
7728 // C++ [over.oper]p8:
7729 // An operator function cannot have default arguments (8.3.6),
7730 // except where explicitly stated below.
7731 //
Mike Stump11289f42009-09-09 15:08:12 +00007732 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007733 // (C++ [over.call]p1).
7734 if (Op != OO_Call) {
7735 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7736 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007737 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00007738 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00007739 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007740 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007741 }
7742 }
7743
Douglas Gregor6cf08062008-11-10 13:38:07 +00007744 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7745 { false, false, false }
7746#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7747 , { Unary, Binary, MemberOnly }
7748#include "clang/Basic/OperatorKinds.def"
7749 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007750
Douglas Gregor6cf08062008-11-10 13:38:07 +00007751 bool CanBeUnaryOperator = OperatorUses[Op][0];
7752 bool CanBeBinaryOperator = OperatorUses[Op][1];
7753 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007754
7755 // C++ [over.oper]p8:
7756 // [...] Operator functions cannot have more or fewer parameters
7757 // than the number required for the corresponding operator, as
7758 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00007759 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00007760 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007761 if (Op != OO_Call &&
7762 ((NumParams == 1 && !CanBeUnaryOperator) ||
7763 (NumParams == 2 && !CanBeBinaryOperator) ||
7764 (NumParams < 1) || (NumParams > 2))) {
7765 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007766 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00007767 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007768 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00007769 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007770 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007771 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00007772 assert(CanBeBinaryOperator &&
7773 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007774 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007775 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007776
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007777 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007778 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007779 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007780
Douglas Gregord69246b2008-11-17 16:14:12 +00007781 // Overloaded operators other than operator() cannot be variadic.
7782 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00007783 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007784 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007785 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007786 }
7787
7788 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00007789 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7790 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007791 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007792 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007793 }
7794
7795 // C++ [over.inc]p1:
7796 // The user-defined function called operator++ implements the
7797 // prefix and postfix ++ operator. If this function is a member
7798 // function with no parameters, or a non-member function with one
7799 // parameter of class or enumeration type, it defines the prefix
7800 // increment operator ++ for objects of that type. If the function
7801 // is a member function with one parameter (which shall be of type
7802 // int) or a non-member function with two parameters (the second
7803 // of which shall be of type int), it defines the postfix
7804 // increment operator ++ for objects of that type.
7805 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7806 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7807 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00007808 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007809 ParamIsInt = BT->getKind() == BuiltinType::Int;
7810
Chris Lattner2b786902008-11-21 07:50:02 +00007811 if (!ParamIsInt)
7812 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00007813 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007814 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007815 }
7816
Douglas Gregord69246b2008-11-17 16:14:12 +00007817 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007818}
Chris Lattner3b024a32008-12-17 07:09:26 +00007819
Alexis Huntc88db062010-01-13 09:01:02 +00007820/// CheckLiteralOperatorDeclaration - Check whether the declaration
7821/// of this literal operator function is well-formed. If so, returns
7822/// false; otherwise, emits appropriate diagnostics and returns true.
7823bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7824 DeclContext *DC = FnDecl->getDeclContext();
7825 Decl::Kind Kind = DC->getDeclKind();
7826 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7827 Kind != Decl::LinkageSpec) {
7828 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7829 << FnDecl->getDeclName();
7830 return true;
7831 }
7832
7833 bool Valid = false;
7834
Alexis Hunt7dd26172010-04-07 23:11:06 +00007835 // template <char...> type operator "" name() is the only valid template
7836 // signature, and the only valid signature with no parameters.
7837 if (FnDecl->param_size() == 0) {
7838 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7839 // Must have only one template parameter
7840 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7841 if (Params->size() == 1) {
7842 NonTypeTemplateParmDecl *PmDecl =
7843 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00007844
Alexis Hunt7dd26172010-04-07 23:11:06 +00007845 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00007846 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7847 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7848 Valid = true;
7849 }
7850 }
7851 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00007852 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00007853 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7854
Alexis Huntc88db062010-01-13 09:01:02 +00007855 QualType T = (*Param)->getType();
7856
Alexis Hunt079a6f72010-04-07 22:57:35 +00007857 // unsigned long long int, long double, and any character type are allowed
7858 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00007859 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7860 Context.hasSameType(T, Context.LongDoubleTy) ||
7861 Context.hasSameType(T, Context.CharTy) ||
7862 Context.hasSameType(T, Context.WCharTy) ||
7863 Context.hasSameType(T, Context.Char16Ty) ||
7864 Context.hasSameType(T, Context.Char32Ty)) {
7865 if (++Param == FnDecl->param_end())
7866 Valid = true;
7867 goto FinishedParams;
7868 }
7869
Alexis Hunt079a6f72010-04-07 22:57:35 +00007870 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00007871 const PointerType *PT = T->getAs<PointerType>();
7872 if (!PT)
7873 goto FinishedParams;
7874 T = PT->getPointeeType();
7875 if (!T.isConstQualified())
7876 goto FinishedParams;
7877 T = T.getUnqualifiedType();
7878
7879 // Move on to the second parameter;
7880 ++Param;
7881
7882 // If there is no second parameter, the first must be a const char *
7883 if (Param == FnDecl->param_end()) {
7884 if (Context.hasSameType(T, Context.CharTy))
7885 Valid = true;
7886 goto FinishedParams;
7887 }
7888
7889 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7890 // are allowed as the first parameter to a two-parameter function
7891 if (!(Context.hasSameType(T, Context.CharTy) ||
7892 Context.hasSameType(T, Context.WCharTy) ||
7893 Context.hasSameType(T, Context.Char16Ty) ||
7894 Context.hasSameType(T, Context.Char32Ty)))
7895 goto FinishedParams;
7896
7897 // The second and final parameter must be an std::size_t
7898 T = (*Param)->getType().getUnqualifiedType();
7899 if (Context.hasSameType(T, Context.getSizeType()) &&
7900 ++Param == FnDecl->param_end())
7901 Valid = true;
7902 }
7903
7904 // FIXME: This diagnostic is absolutely terrible.
7905FinishedParams:
7906 if (!Valid) {
7907 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7908 << FnDecl->getDeclName();
7909 return true;
7910 }
7911
7912 return false;
7913}
7914
Douglas Gregor07665a62009-01-05 19:45:36 +00007915/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7916/// linkage specification, including the language and (if present)
7917/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7918/// the location of the language string literal, which is provided
7919/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7920/// the '{' brace. Otherwise, this linkage specification does not
7921/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00007922Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7923 SourceLocation LangLoc,
7924 llvm::StringRef Lang,
7925 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00007926 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007927 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007928 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007929 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007930 Language = LinkageSpecDecl::lang_cxx;
7931 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00007932 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00007933 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00007934 }
Mike Stump11289f42009-09-09 15:08:12 +00007935
Chris Lattner438e5012008-12-17 07:13:27 +00007936 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00007937
Douglas Gregor07665a62009-01-05 19:45:36 +00007938 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007939 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007940 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00007941 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00007942 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00007943}
7944
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00007945/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00007946/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7947/// valid, it's the position of the closing '}' brace in a linkage
7948/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00007949Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007950 Decl *LinkageSpec,
7951 SourceLocation RBraceLoc) {
7952 if (LinkageSpec) {
7953 if (RBraceLoc.isValid()) {
7954 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7955 LSDecl->setRBraceLoc(RBraceLoc);
7956 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007957 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007958 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007959 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00007960}
7961
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007962/// \brief Perform semantic analysis for the variable declaration that
7963/// occurs within a C++ catch clause, returning the newly-created
7964/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007965VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00007966 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007967 SourceLocation StartLoc,
7968 SourceLocation Loc,
7969 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007970 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007971 QualType ExDeclType = TInfo->getType();
7972
Sebastian Redl54c04d42008-12-22 19:15:10 +00007973 // Arrays and functions decay.
7974 if (ExDeclType->isArrayType())
7975 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7976 else if (ExDeclType->isFunctionType())
7977 ExDeclType = Context.getPointerType(ExDeclType);
7978
7979 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7980 // The exception-declaration shall not denote a pointer or reference to an
7981 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00007982 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00007983 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007984 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00007985 Invalid = true;
7986 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007987
Douglas Gregor104ee002010-03-08 01:47:36 +00007988 // GCC allows catching pointers and references to incomplete types
7989 // as an extension; so do we, but we warn by default.
7990
Sebastian Redl54c04d42008-12-22 19:15:10 +00007991 QualType BaseType = ExDeclType;
7992 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00007993 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00007994 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007995 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007996 BaseType = Ptr->getPointeeType();
7997 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00007998 DK = diag::ext_catch_incomplete_ptr;
7999 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00008000 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00008001 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008002 BaseType = Ref->getPointeeType();
8003 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00008004 DK = diag::ext_catch_incomplete_ref;
8005 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008006 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00008007 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00008008 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8009 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00008010 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008011
Mike Stump11289f42009-09-09 15:08:12 +00008012 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008013 RequireNonAbstractType(Loc, ExDeclType,
8014 diag::err_abstract_type_in_decl,
8015 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00008016 Invalid = true;
8017
John McCall2ca705e2010-07-24 00:37:23 +00008018 // Only the non-fragile NeXT runtime currently supports C++ catches
8019 // of ObjC types, and no runtime supports catching ObjC types by value.
8020 if (!Invalid && getLangOptions().ObjC1) {
8021 QualType T = ExDeclType;
8022 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8023 T = RT->getPointeeType();
8024
8025 if (T->isObjCObjectType()) {
8026 Diag(Loc, diag::err_objc_object_catch);
8027 Invalid = true;
8028 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00008029 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00008030 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8031 Invalid = true;
8032 }
8033 }
8034 }
8035
Abramo Bagnaradff19302011-03-08 08:55:46 +00008036 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8037 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00008038 ExDecl->setExceptionVariable(true);
8039
Douglas Gregor6de584c2010-03-05 23:38:39 +00008040 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00008041 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00008042 // C++ [except.handle]p16:
8043 // The object declared in an exception-declaration or, if the
8044 // exception-declaration does not specify a name, a temporary (12.2) is
8045 // copy-initialized (8.5) from the exception object. [...]
8046 // The object is destroyed when the handler exits, after the destruction
8047 // of any automatic objects initialized within the handler.
8048 //
8049 // We just pretend to initialize the object with itself, then make sure
8050 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00008051 QualType initType = ExDeclType;
8052
8053 InitializedEntity entity =
8054 InitializedEntity::InitializeVariable(ExDecl);
8055 InitializationKind initKind =
8056 InitializationKind::CreateCopy(Loc, SourceLocation());
8057
8058 Expr *opaqueValue =
8059 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8060 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8061 ExprResult result = sequence.Perform(*this, entity, initKind,
8062 MultiExprArg(&opaqueValue, 1));
8063 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00008064 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00008065 else {
8066 // If the constructor used was non-trivial, set this as the
8067 // "initializer".
8068 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8069 if (!construct->getConstructor()->isTrivial()) {
8070 Expr *init = MaybeCreateExprWithCleanups(construct);
8071 ExDecl->setInit(init);
8072 }
8073
8074 // And make sure it's destructable.
8075 FinalizeVarWithDestructor(ExDecl, recordType);
8076 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00008077 }
8078 }
8079
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008080 if (Invalid)
8081 ExDecl->setInvalidDecl();
8082
8083 return ExDecl;
8084}
8085
8086/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8087/// handler.
John McCall48871652010-08-21 09:40:31 +00008088Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00008089 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00008090 bool Invalid = D.isInvalidType();
8091
8092 // Check for unexpanded parameter packs.
8093 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8094 UPPC_ExceptionType)) {
8095 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8096 D.getIdentifierLoc());
8097 Invalid = true;
8098 }
8099
Sebastian Redl54c04d42008-12-22 19:15:10 +00008100 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008101 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00008102 LookupOrdinaryName,
8103 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008104 // The scope should be freshly made just for us. There is just no way
8105 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00008106 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00008107 if (PrevDecl->isTemplateParameter()) {
8108 // Maybe we will complain about the shadowed template parameter.
8109 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008110 }
8111 }
8112
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008113 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008114 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8115 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008116 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008117 }
8118
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008119 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008120 D.getSourceRange().getBegin(),
8121 D.getIdentifierLoc(),
8122 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008123 if (Invalid)
8124 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00008125
Sebastian Redl54c04d42008-12-22 19:15:10 +00008126 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008127 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008128 PushOnScopeChains(ExDecl, S);
8129 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008130 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008131
Douglas Gregor758a8692009-06-17 21:51:59 +00008132 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00008133 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008134}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008135
Abramo Bagnaraea947882011-03-08 16:41:52 +00008136Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00008137 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00008138 Expr *AssertMessageExpr_,
8139 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00008140 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008141
Anders Carlsson54b26982009-03-14 00:33:21 +00008142 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8143 llvm::APSInt Value(32);
8144 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008145 Diag(StaticAssertLoc,
8146 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00008147 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008148 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00008149 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008150
Anders Carlsson54b26982009-03-14 00:33:21 +00008151 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008152 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00008153 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00008154 }
8155 }
Mike Stump11289f42009-09-09 15:08:12 +00008156
Douglas Gregoref68fee2010-12-15 23:55:21 +00008157 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8158 return 0;
8159
Abramo Bagnaraea947882011-03-08 16:41:52 +00008160 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8161 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00008162
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008163 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00008164 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008165}
Sebastian Redlf769df52009-03-24 22:27:57 +00008166
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008167/// \brief Perform semantic analysis of the given friend type declaration.
8168///
8169/// \returns A friend declaration that.
8170FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8171 TypeSourceInfo *TSInfo) {
8172 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8173
8174 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008175 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008176
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008177 if (!getLangOptions().CPlusPlus0x) {
8178 // C++03 [class.friend]p2:
8179 // An elaborated-type-specifier shall be used in a friend declaration
8180 // for a class.*
8181 //
8182 // * The class-key of the elaborated-type-specifier is required.
8183 if (!ActiveTemplateInstantiations.empty()) {
8184 // Do not complain about the form of friend template types during
8185 // template instantiation; we will already have complained when the
8186 // template was declared.
8187 } else if (!T->isElaboratedTypeSpecifier()) {
8188 // If we evaluated the type to a record type, suggest putting
8189 // a tag in front.
8190 if (const RecordType *RT = T->getAs<RecordType>()) {
8191 RecordDecl *RD = RT->getDecl();
8192
8193 std::string InsertionText = std::string(" ") + RD->getKindName();
8194
8195 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8196 << (unsigned) RD->getTagKind()
8197 << T
8198 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8199 InsertionText);
8200 } else {
8201 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8202 << T
8203 << SourceRange(FriendLoc, TypeRange.getEnd());
8204 }
8205 } else if (T->getAs<EnumType>()) {
8206 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008207 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008208 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008209 }
8210 }
8211
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008212 // C++0x [class.friend]p3:
8213 // If the type specifier in a friend declaration designates a (possibly
8214 // cv-qualified) class type, that class is declared as a friend; otherwise,
8215 // the friend declaration is ignored.
8216
8217 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8218 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008219
8220 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8221}
8222
John McCallace48cd2010-10-19 01:40:49 +00008223/// Handle a friend tag declaration where the scope specifier was
8224/// templated.
8225Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8226 unsigned TagSpec, SourceLocation TagLoc,
8227 CXXScopeSpec &SS,
8228 IdentifierInfo *Name, SourceLocation NameLoc,
8229 AttributeList *Attr,
8230 MultiTemplateParamsArg TempParamLists) {
8231 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8232
8233 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00008234 bool Invalid = false;
8235
8236 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008237 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00008238 TempParamLists.get(),
8239 TempParamLists.size(),
8240 /*friend*/ true,
8241 isExplicitSpecialization,
8242 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00008243 if (TemplateParams->size() > 0) {
8244 // This is a declaration of a class template.
8245 if (Invalid)
8246 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008247
John McCallace48cd2010-10-19 01:40:49 +00008248 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8249 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008250 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008251 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008252 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00008253 } else {
8254 // The "template<>" header is extraneous.
8255 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8256 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8257 isExplicitSpecialization = true;
8258 }
8259 }
8260
8261 if (Invalid) return 0;
8262
8263 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8264
8265 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00008266 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00008267 if (TempParamLists.get()[I]->size()) {
8268 isAllExplicitSpecializations = false;
8269 break;
8270 }
8271 }
8272
8273 // FIXME: don't ignore attributes.
8274
8275 // If it's explicit specializations all the way down, just forget
8276 // about the template header and build an appropriate non-templated
8277 // friend. TODO: for source fidelity, remember the headers.
8278 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008279 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00008280 ElaboratedTypeKeyword Keyword
8281 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008282 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008283 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00008284 if (T.isNull())
8285 return 0;
8286
8287 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8288 if (isa<DependentNameType>(T)) {
8289 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8290 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008291 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008292 TL.setNameLoc(NameLoc);
8293 } else {
8294 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8295 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008296 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008297 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8298 }
8299
8300 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8301 TSI, FriendLoc);
8302 Friend->setAccess(AS_public);
8303 CurContext->addDecl(Friend);
8304 return Friend;
8305 }
8306
8307 // Handle the case of a templated-scope friend class. e.g.
8308 // template <class T> class A<T>::B;
8309 // FIXME: we don't support these right now.
8310 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8311 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8312 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8313 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8314 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008315 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00008316 TL.setNameLoc(NameLoc);
8317
8318 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8319 TSI, FriendLoc);
8320 Friend->setAccess(AS_public);
8321 Friend->setUnsupportedFriend(true);
8322 CurContext->addDecl(Friend);
8323 return Friend;
8324}
8325
8326
John McCall11083da2009-09-16 22:47:08 +00008327/// Handle a friend type declaration. This works in tandem with
8328/// ActOnTag.
8329///
8330/// Notes on friend class templates:
8331///
8332/// We generally treat friend class declarations as if they were
8333/// declaring a class. So, for example, the elaborated type specifier
8334/// in a friend declaration is required to obey the restrictions of a
8335/// class-head (i.e. no typedefs in the scope chain), template
8336/// parameters are required to match up with simple template-ids, &c.
8337/// However, unlike when declaring a template specialization, it's
8338/// okay to refer to a template specialization without an empty
8339/// template parameter declaration, e.g.
8340/// friend class A<T>::B<unsigned>;
8341/// We permit this as a special case; if there are any template
8342/// parameters present at all, require proper matching, i.e.
8343/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00008344Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00008345 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008346 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00008347
8348 assert(DS.isFriendSpecified());
8349 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8350
John McCall11083da2009-09-16 22:47:08 +00008351 // Try to convert the decl specifier to a type. This works for
8352 // friend templates because ActOnTag never produces a ClassTemplateDecl
8353 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00008354 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00008355 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8356 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00008357 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00008358 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008359
Douglas Gregor6c110f32010-12-16 01:14:37 +00008360 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8361 return 0;
8362
John McCall11083da2009-09-16 22:47:08 +00008363 // This is definitely an error in C++98. It's probably meant to
8364 // be forbidden in C++0x, too, but the specification is just
8365 // poorly written.
8366 //
8367 // The problem is with declarations like the following:
8368 // template <T> friend A<T>::foo;
8369 // where deciding whether a class C is a friend or not now hinges
8370 // on whether there exists an instantiation of A that causes
8371 // 'foo' to equal C. There are restrictions on class-heads
8372 // (which we declare (by fiat) elaborated friend declarations to
8373 // be) that makes this tractable.
8374 //
8375 // FIXME: handle "template <> friend class A<T>;", which
8376 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00008377 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00008378 Diag(Loc, diag::err_tagless_friend_type_template)
8379 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008380 return 0;
John McCall11083da2009-09-16 22:47:08 +00008381 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008382
John McCallaa74a0c2009-08-28 07:59:38 +00008383 // C++98 [class.friend]p1: A friend of a class is a function
8384 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00008385 // This is fixed in DR77, which just barely didn't make the C++03
8386 // deadline. It's also a very silly restriction that seriously
8387 // affects inner classes and which nobody else seems to implement;
8388 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00008389 //
8390 // But note that we could warn about it: it's always useless to
8391 // friend one of your own members (it's not, however, worthless to
8392 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00008393
John McCall11083da2009-09-16 22:47:08 +00008394 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008395 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00008396 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008397 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00008398 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00008399 TSI,
John McCall11083da2009-09-16 22:47:08 +00008400 DS.getFriendSpecLoc());
8401 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008402 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8403
8404 if (!D)
John McCall48871652010-08-21 09:40:31 +00008405 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008406
John McCall11083da2009-09-16 22:47:08 +00008407 D->setAccess(AS_public);
8408 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00008409
John McCall48871652010-08-21 09:40:31 +00008410 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00008411}
8412
John McCallde3fd222010-10-12 23:13:28 +00008413Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8414 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008415 const DeclSpec &DS = D.getDeclSpec();
8416
8417 assert(DS.isFriendSpecified());
8418 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8419
8420 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00008421 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8422 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00008423
8424 // C++ [class.friend]p1
8425 // A friend of a class is a function or class....
8426 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00008427 // It *doesn't* see through dependent types, which is correct
8428 // according to [temp.arg.type]p3:
8429 // If a declaration acquires a function type through a
8430 // type dependent on a template-parameter and this causes
8431 // a declaration that does not use the syntactic form of a
8432 // function declarator to have a function type, the program
8433 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00008434 if (!T->isFunctionType()) {
8435 Diag(Loc, diag::err_unexpected_friend);
8436
8437 // It might be worthwhile to try to recover by creating an
8438 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00008439 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008440 }
8441
8442 // C++ [namespace.memdef]p3
8443 // - If a friend declaration in a non-local class first declares a
8444 // class or function, the friend class or function is a member
8445 // of the innermost enclosing namespace.
8446 // - The name of the friend is not found by simple name lookup
8447 // until a matching declaration is provided in that namespace
8448 // scope (either before or after the class declaration granting
8449 // friendship).
8450 // - If a friend function is called, its name may be found by the
8451 // name lookup that considers functions from namespaces and
8452 // classes associated with the types of the function arguments.
8453 // - When looking for a prior declaration of a class or a function
8454 // declared as a friend, scopes outside the innermost enclosing
8455 // namespace scope are not considered.
8456
John McCallde3fd222010-10-12 23:13:28 +00008457 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008458 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8459 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00008460 assert(Name);
8461
Douglas Gregor6c110f32010-12-16 01:14:37 +00008462 // Check for unexpanded parameter packs.
8463 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8464 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8465 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8466 return 0;
8467
John McCall07e91c02009-08-06 02:15:43 +00008468 // The context we found the declaration in, or in which we should
8469 // create the declaration.
8470 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00008471 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008472 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00008473 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00008474
John McCallde3fd222010-10-12 23:13:28 +00008475 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00008476
John McCallde3fd222010-10-12 23:13:28 +00008477 // There are four cases here.
8478 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00008479 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00008480 // there as appropriate.
8481 // Recover from invalid scope qualifiers as if they just weren't there.
8482 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00008483 // C++0x [namespace.memdef]p3:
8484 // If the name in a friend declaration is neither qualified nor
8485 // a template-id and the declaration is a function or an
8486 // elaborated-type-specifier, the lookup to determine whether
8487 // the entity has been previously declared shall not consider
8488 // any scopes outside the innermost enclosing namespace.
8489 // C++0x [class.friend]p11:
8490 // If a friend declaration appears in a local class and the name
8491 // specified is an unqualified name, a prior declaration is
8492 // looked up without considering scopes that are outside the
8493 // innermost enclosing non-class scope. For a friend function
8494 // declaration, if there is no prior declaration, the program is
8495 // ill-formed.
8496 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00008497 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00008498
John McCallf7cfb222010-10-13 05:45:15 +00008499 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00008500 DC = CurContext;
8501 while (true) {
8502 // Skip class contexts. If someone can cite chapter and verse
8503 // for this behavior, that would be nice --- it's what GCC and
8504 // EDG do, and it seems like a reasonable intent, but the spec
8505 // really only says that checks for unqualified existing
8506 // declarations should stop at the nearest enclosing namespace,
8507 // not that they should only consider the nearest enclosing
8508 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008509 while (DC->isRecord())
8510 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00008511
John McCall1f82f242009-11-18 22:49:29 +00008512 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00008513
8514 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00008515 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00008516 break;
John McCallf7cfb222010-10-13 05:45:15 +00008517
John McCallf4776592010-10-14 22:22:28 +00008518 if (isTemplateId) {
8519 if (isa<TranslationUnitDecl>(DC)) break;
8520 } else {
8521 if (DC->isFileContext()) break;
8522 }
John McCall07e91c02009-08-06 02:15:43 +00008523 DC = DC->getParent();
8524 }
8525
8526 // C++ [class.friend]p1: A friend of a class is a function or
8527 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00008528 // C++0x changes this for both friend types and functions.
8529 // Most C++ 98 compilers do seem to give an error here, so
8530 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00008531 if (!Previous.empty() && DC->Equals(CurContext)
8532 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00008533 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00008534
John McCallccbc0322010-10-13 06:22:15 +00008535 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00008536
John McCallde3fd222010-10-12 23:13:28 +00008537 // - There's a non-dependent scope specifier, in which case we
8538 // compute it and do a previous lookup there for a function
8539 // or function template.
8540 } else if (!SS.getScopeRep()->isDependent()) {
8541 DC = computeDeclContext(SS);
8542 if (!DC) return 0;
8543
8544 if (RequireCompleteDeclContext(SS, DC)) return 0;
8545
8546 LookupQualifiedName(Previous, DC);
8547
8548 // Ignore things found implicitly in the wrong scope.
8549 // TODO: better diagnostics for this case. Suggesting the right
8550 // qualified scope would be nice...
8551 LookupResult::Filter F = Previous.makeFilter();
8552 while (F.hasNext()) {
8553 NamedDecl *D = F.next();
8554 if (!DC->InEnclosingNamespaceSetOf(
8555 D->getDeclContext()->getRedeclContext()))
8556 F.erase();
8557 }
8558 F.done();
8559
8560 if (Previous.empty()) {
8561 D.setInvalidType();
8562 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8563 return 0;
8564 }
8565
8566 // C++ [class.friend]p1: A friend of a class is a function or
8567 // class that is not a member of the class . . .
8568 if (DC->Equals(CurContext))
8569 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8570
8571 // - There's a scope specifier that does not match any template
8572 // parameter lists, in which case we use some arbitrary context,
8573 // create a method or method template, and wait for instantiation.
8574 // - There's a scope specifier that does match some template
8575 // parameter lists, which we don't handle right now.
8576 } else {
8577 DC = CurContext;
8578 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00008579 }
8580
John McCallf7cfb222010-10-13 05:45:15 +00008581 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00008582 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00008583 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8584 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8585 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00008586 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00008587 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8588 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00008589 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008590 }
John McCall07e91c02009-08-06 02:15:43 +00008591 }
8592
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008593 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00008594 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00008595 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00008596 IsDefinition,
8597 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00008598 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00008599
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008600 assert(ND->getDeclContext() == DC);
8601 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00008602
John McCall759e32b2009-08-31 22:39:49 +00008603 // Add the function declaration to the appropriate lookup tables,
8604 // adjusting the redeclarations list as necessary. We don't
8605 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00008606 //
John McCall759e32b2009-08-31 22:39:49 +00008607 // Also update the scope-based lookup if the target context's
8608 // lookup context is in lexical scope.
8609 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008610 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008611 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008612 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008613 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008614 }
John McCallaa74a0c2009-08-28 07:59:38 +00008615
8616 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008617 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00008618 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00008619 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00008620 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00008621
John McCallde3fd222010-10-12 23:13:28 +00008622 if (ND->isInvalidDecl())
8623 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00008624 else {
8625 FunctionDecl *FD;
8626 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8627 FD = FTD->getTemplatedDecl();
8628 else
8629 FD = cast<FunctionDecl>(ND);
8630
8631 // Mark templated-scope function declarations as unsupported.
8632 if (FD->getNumTemplateParameterLists())
8633 FrD->setUnsupportedFriend(true);
8634 }
John McCallde3fd222010-10-12 23:13:28 +00008635
John McCall48871652010-08-21 09:40:31 +00008636 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00008637}
8638
John McCall48871652010-08-21 09:40:31 +00008639void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8640 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00008641
Sebastian Redlf769df52009-03-24 22:27:57 +00008642 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8643 if (!Fn) {
8644 Diag(DelLoc, diag::err_deleted_non_function);
8645 return;
8646 }
8647 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8648 Diag(DelLoc, diag::err_deleted_decl_not_first);
8649 Diag(Prev->getLocation(), diag::note_previous_declaration);
8650 // If the declaration wasn't the first, we delete the function anyway for
8651 // recovery.
8652 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008653 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00008654}
Sebastian Redl4c018662009-04-27 21:33:24 +00008655
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008656void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8657 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8658
8659 if (MD) {
8660 CXXSpecialMember Member = getSpecialMember(MD);
8661 if (Member == CXXInvalid) {
8662 Diag(DefaultLoc, diag::err_default_special_members);
8663 return;
8664 }
8665
8666 MD->setDefaulted();
8667 MD->setExplicitlyDefaulted();
8668
8669 // We'll check it when the record is done
8670 if (MD == MD->getCanonicalDecl())
8671 return;
8672
8673 switch (Member) {
8674 case CXXDefaultConstructor: {
8675 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8676 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008677 if (!CD->isInvalidDecl())
8678 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8679 break;
8680 }
8681
8682 case CXXCopyConstructor: {
8683 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8684 CheckExplicitlyDefaultedCopyConstructor(CD);
8685 if (!CD->isInvalidDecl())
8686 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008687 break;
8688 }
Alexis Huntf91729462011-05-12 22:46:25 +00008689
Alexis Huntc9a55732011-05-14 05:23:28 +00008690 case CXXCopyAssignment: {
8691 CheckExplicitlyDefaultedCopyAssignment(MD);
8692 if (!MD->isInvalidDecl())
8693 DefineImplicitCopyAssignment(DefaultLoc, MD);
8694 break;
8695 }
8696
Alexis Huntf91729462011-05-12 22:46:25 +00008697 case CXXDestructor: {
8698 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8699 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008700 if (!DD->isInvalidDecl())
8701 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00008702 break;
8703 }
8704
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008705 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00008706 // FIXME: Do the rest once we have move functions
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008707 break;
8708 }
8709 } else {
8710 Diag(DefaultLoc, diag::err_default_special_members);
8711 }
8712}
8713
Sebastian Redl4c018662009-04-27 21:33:24 +00008714static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00008715 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00008716 Stmt *SubStmt = *CI;
8717 if (!SubStmt)
8718 continue;
8719 if (isa<ReturnStmt>(SubStmt))
8720 Self.Diag(SubStmt->getSourceRange().getBegin(),
8721 diag::err_return_in_constructor_handler);
8722 if (!isa<Expr>(SubStmt))
8723 SearchForReturnInStmt(Self, SubStmt);
8724 }
8725}
8726
8727void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8728 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8729 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8730 SearchForReturnInStmt(*this, Handler);
8731 }
8732}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008733
Mike Stump11289f42009-09-09 15:08:12 +00008734bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008735 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00008736 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8737 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008738
Chandler Carruth284bb2e2010-02-15 11:53:20 +00008739 if (Context.hasSameType(NewTy, OldTy) ||
8740 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008741 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008742
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008743 // Check if the return types are covariant
8744 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00008745
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008746 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008747 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8748 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008749 NewClassTy = NewPT->getPointeeType();
8750 OldClassTy = OldPT->getPointeeType();
8751 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008752 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8753 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8754 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8755 NewClassTy = NewRT->getPointeeType();
8756 OldClassTy = OldRT->getPointeeType();
8757 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008758 }
8759 }
Mike Stump11289f42009-09-09 15:08:12 +00008760
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008761 // The return types aren't either both pointers or references to a class type.
8762 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00008763 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008764 diag::err_different_return_type_for_overriding_virtual_function)
8765 << New->getDeclName() << NewTy << OldTy;
8766 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00008767
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008768 return true;
8769 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008770
Anders Carlssone60365b2009-12-31 18:34:24 +00008771 // C++ [class.virtual]p6:
8772 // If the return type of D::f differs from the return type of B::f, the
8773 // class type in the return type of D::f shall be complete at the point of
8774 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008775 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8776 if (!RT->isBeingDefined() &&
8777 RequireCompleteType(New->getLocation(), NewClassTy,
8778 PDiag(diag::err_covariant_return_incomplete)
8779 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00008780 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008781 }
Anders Carlssone60365b2009-12-31 18:34:24 +00008782
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008783 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008784 // Check if the new class derives from the old class.
8785 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8786 Diag(New->getLocation(),
8787 diag::err_covariant_return_not_derived)
8788 << New->getDeclName() << NewTy << OldTy;
8789 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8790 return true;
8791 }
Mike Stump11289f42009-09-09 15:08:12 +00008792
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008793 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00008794 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00008795 diag::err_covariant_return_inaccessible_base,
8796 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8797 // FIXME: Should this point to the return type?
8798 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00008799 // FIXME: this note won't trigger for delayed access control
8800 // diagnostics, and it's impossible to get an undelayed error
8801 // here from access control during the original parse because
8802 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008803 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8804 return true;
8805 }
8806 }
Mike Stump11289f42009-09-09 15:08:12 +00008807
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008808 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008809 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008810 Diag(New->getLocation(),
8811 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008812 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008813 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8814 return true;
8815 };
Mike Stump11289f42009-09-09 15:08:12 +00008816
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008817
8818 // The new class type must have the same or less qualifiers as the old type.
8819 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8820 Diag(New->getLocation(),
8821 diag::err_covariant_return_type_class_type_more_qualified)
8822 << New->getDeclName() << NewTy << OldTy;
8823 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8824 return true;
8825 };
Mike Stump11289f42009-09-09 15:08:12 +00008826
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008827 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008828}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008829
Douglas Gregor21920e372009-12-01 17:24:26 +00008830/// \brief Mark the given method pure.
8831///
8832/// \param Method the method to be marked pure.
8833///
8834/// \param InitRange the source range that covers the "0" initializer.
8835bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008836 SourceLocation EndLoc = InitRange.getEnd();
8837 if (EndLoc.isValid())
8838 Method->setRangeEnd(EndLoc);
8839
Douglas Gregor21920e372009-12-01 17:24:26 +00008840 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8841 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00008842 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008843 }
Douglas Gregor21920e372009-12-01 17:24:26 +00008844
8845 if (!Method->isInvalidDecl())
8846 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8847 << Method->getDeclName() << InitRange;
8848 return true;
8849}
8850
John McCall1f4ee7b2009-12-19 09:28:58 +00008851/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8852/// an initializer for the out-of-line declaration 'Dcl'. The scope
8853/// is a fresh scope pushed for just this purpose.
8854///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008855/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8856/// static data member of class X, names should be looked up in the scope of
8857/// class X.
John McCall48871652010-08-21 09:40:31 +00008858void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008859 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008860 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008861
John McCall1f4ee7b2009-12-19 09:28:58 +00008862 // We should only get called for declarations with scope specifiers, like:
8863 // int foo::bar;
8864 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008865 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008866}
8867
8868/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00008869/// initializer for the out-of-line declaration 'D'.
8870void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008871 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008872 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008873
John McCall1f4ee7b2009-12-19 09:28:58 +00008874 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008875 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008876}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008877
8878/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8879/// C++ if/switch/while/for statement.
8880/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00008881DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008882 // C++ 6.4p2:
8883 // The declarator shall not specify a function or an array.
8884 // The type-specifier-seq shall not contain typedef and shall not declare a
8885 // new class or enumeration.
8886 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8887 "Parser allowed 'typedef' as storage class of condition decl.");
8888
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008889 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00008890 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
8891 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008892
8893 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
8894 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
8895 // would be created and CXXConditionDeclExpr wants a VarDecl.
8896 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
8897 << D.getSourceRange();
8898 return DeclResult();
8899 } else if (OwnedTag && OwnedTag->isDefinition()) {
8900 // The type-specifier-seq shall not declare a new class or enumeration.
8901 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
8902 }
8903
John McCall48871652010-08-21 09:40:31 +00008904 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008905 if (!Dcl)
8906 return DeclResult();
8907
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008908 return Dcl;
8909}
Anders Carlssonf98849e2009-12-02 17:15:43 +00008910
Douglas Gregor88d292c2010-05-13 16:44:06 +00008911void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8912 bool DefinitionRequired) {
8913 // Ignore any vtable uses in unevaluated operands or for classes that do
8914 // not have a vtable.
8915 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8916 CurContext->isDependentContext() ||
8917 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00008918 return;
8919
Douglas Gregor88d292c2010-05-13 16:44:06 +00008920 // Try to insert this class into the map.
8921 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8922 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8923 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8924 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00008925 // If we already had an entry, check to see if we are promoting this vtable
8926 // to required a definition. If so, we need to reappend to the VTableUses
8927 // list, since we may have already processed the first entry.
8928 if (DefinitionRequired && !Pos.first->second) {
8929 Pos.first->second = true;
8930 } else {
8931 // Otherwise, we can early exit.
8932 return;
8933 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008934 }
8935
8936 // Local classes need to have their virtual members marked
8937 // immediately. For all other classes, we mark their virtual members
8938 // at the end of the translation unit.
8939 if (Class->isLocalClass())
8940 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00008941 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00008942 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00008943}
8944
Douglas Gregor88d292c2010-05-13 16:44:06 +00008945bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008946 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00008947 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00008948
Douglas Gregor88d292c2010-05-13 16:44:06 +00008949 // Note: The VTableUses vector could grow as a result of marking
8950 // the members of a class as "used", so we check the size each
8951 // time through the loop and prefer indices (with are stable) to
8952 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00008953 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00008954 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00008955 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00008956 if (!Class)
8957 continue;
8958
8959 SourceLocation Loc = VTableUses[I].second;
8960
8961 // If this class has a key function, but that key function is
8962 // defined in another translation unit, we don't need to emit the
8963 // vtable even though we're using it.
8964 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00008965 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008966 switch (KeyFunction->getTemplateSpecializationKind()) {
8967 case TSK_Undeclared:
8968 case TSK_ExplicitSpecialization:
8969 case TSK_ExplicitInstantiationDeclaration:
8970 // The key function is in another translation unit.
8971 continue;
8972
8973 case TSK_ExplicitInstantiationDefinition:
8974 case TSK_ImplicitInstantiation:
8975 // We will be instantiating the key function.
8976 break;
8977 }
8978 } else if (!KeyFunction) {
8979 // If we have a class with no key function that is the subject
8980 // of an explicit instantiation declaration, suppress the
8981 // vtable; it will live with the explicit instantiation
8982 // definition.
8983 bool IsExplicitInstantiationDeclaration
8984 = Class->getTemplateSpecializationKind()
8985 == TSK_ExplicitInstantiationDeclaration;
8986 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
8987 REnd = Class->redecls_end();
8988 R != REnd; ++R) {
8989 TemplateSpecializationKind TSK
8990 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
8991 if (TSK == TSK_ExplicitInstantiationDeclaration)
8992 IsExplicitInstantiationDeclaration = true;
8993 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8994 IsExplicitInstantiationDeclaration = false;
8995 break;
8996 }
8997 }
8998
8999 if (IsExplicitInstantiationDeclaration)
9000 continue;
9001 }
9002
9003 // Mark all of the virtual members of this class as referenced, so
9004 // that we can build a vtable. Then, tell the AST consumer that a
9005 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00009006 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009007 MarkVirtualMembersReferenced(Loc, Class);
9008 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9009 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9010
9011 // Optionally warn if we're emitting a weak vtable.
9012 if (Class->getLinkage() == ExternalLinkage &&
9013 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009014 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00009015 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9016 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00009017 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009018 VTableUses.clear();
9019
Douglas Gregor97509692011-04-22 22:25:37 +00009020 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00009021}
Anders Carlsson82fccd02009-12-07 08:24:59 +00009022
Rafael Espindola5b334082010-03-26 00:36:59 +00009023void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9024 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00009025 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9026 e = RD->method_end(); i != e; ++i) {
9027 CXXMethodDecl *MD = *i;
9028
9029 // C++ [basic.def.odr]p2:
9030 // [...] A virtual member function is used if it is not pure. [...]
9031 if (MD->isVirtual() && !MD->isPure())
9032 MarkDeclarationReferenced(Loc, MD);
9033 }
Rafael Espindola5b334082010-03-26 00:36:59 +00009034
9035 // Only classes that have virtual bases need a VTT.
9036 if (RD->getNumVBases() == 0)
9037 return;
9038
9039 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9040 e = RD->bases_end(); i != e; ++i) {
9041 const CXXRecordDecl *Base =
9042 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00009043 if (Base->getNumVBases() == 0)
9044 continue;
9045 MarkVirtualMembersReferenced(Loc, Base);
9046 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00009047}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009048
9049/// SetIvarInitializers - This routine builds initialization ASTs for the
9050/// Objective-C implementation whose ivars need be initialized.
9051void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9052 if (!getLangOptions().CPlusPlus)
9053 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00009054 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009055 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9056 CollectIvarsToConstructOrDestruct(OID, ivars);
9057 if (ivars.empty())
9058 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00009059 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009060 for (unsigned i = 0; i < ivars.size(); i++) {
9061 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00009062 if (Field->isInvalidDecl())
9063 continue;
9064
Alexis Hunt1d792652011-01-08 20:30:50 +00009065 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009066 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9067 InitializationKind InitKind =
9068 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9069
9070 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00009071 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00009072 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00009073 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009074 // Note, MemberInit could actually come back empty if no initialization
9075 // is required (e.g., because it would call a trivial default constructor)
9076 if (!MemberInit.get() || MemberInit.isInvalid())
9077 continue;
John McCallacf0ee52010-10-08 02:01:28 +00009078
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009079 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00009080 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9081 SourceLocation(),
9082 MemberInit.takeAs<Expr>(),
9083 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009084 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00009085
9086 // Be sure that the destructor is accessible and is marked as referenced.
9087 if (const RecordType *RecordTy
9088 = Context.getBaseElementType(Field->getType())
9089 ->getAs<RecordType>()) {
9090 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00009091 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00009092 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9093 CheckDestructorAccess(Field->getLocation(), Destructor,
9094 PDiag(diag::err_access_dtor_ivar)
9095 << Context.getBaseElementType(Field->getType()));
9096 }
9097 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009098 }
9099 ObjCImplementation->setIvarInitializers(Context,
9100 AllToInit.data(), AllToInit.size());
9101 }
9102}
Alexis Hunt6118d662011-05-04 05:57:24 +00009103
Alexis Hunt27a761d2011-05-04 23:29:54 +00009104static
9105void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9106 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9107 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9108 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9109 Sema &S) {
9110 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9111 CE = Current.end();
9112 if (Ctor->isInvalidDecl())
9113 return;
9114
9115 const FunctionDecl *FNTarget = 0;
9116 CXXConstructorDecl *Target;
9117
9118 // We ignore the result here since if we don't have a body, Target will be
9119 // null below.
9120 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9121 Target
9122= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9123
9124 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9125 // Avoid dereferencing a null pointer here.
9126 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9127
9128 if (!Current.insert(Canonical))
9129 return;
9130
9131 // We know that beyond here, we aren't chaining into a cycle.
9132 if (!Target || !Target->isDelegatingConstructor() ||
9133 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9134 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9135 Valid.insert(*CI);
9136 Current.clear();
9137 // We've hit a cycle.
9138 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9139 Current.count(TCanonical)) {
9140 // If we haven't diagnosed this cycle yet, do so now.
9141 if (!Invalid.count(TCanonical)) {
9142 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00009143 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00009144 << Ctor;
9145
9146 // Don't add a note for a function delegating directo to itself.
9147 if (TCanonical != Canonical)
9148 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9149
9150 CXXConstructorDecl *C = Target;
9151 while (C->getCanonicalDecl() != Canonical) {
9152 (void)C->getTargetConstructor()->hasBody(FNTarget);
9153 assert(FNTarget && "Ctor cycle through bodiless function");
9154
9155 C
9156 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9157 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9158 }
9159 }
9160
9161 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9162 Invalid.insert(*CI);
9163 Current.clear();
9164 } else {
9165 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9166 }
9167}
9168
9169
Alexis Hunt6118d662011-05-04 05:57:24 +00009170void Sema::CheckDelegatingCtorCycles() {
9171 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9172
Alexis Hunt27a761d2011-05-04 23:29:54 +00009173 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9174 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00009175
9176 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00009177 I = DelegatingCtorDecls.begin(),
9178 E = DelegatingCtorDecls.end();
9179 I != E; ++I) {
9180 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00009181 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00009182
9183 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9184 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00009185}