blob: 4f9c0493c674890e8c9c32e883aff377b1d12344 [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");
Richard Smith938f40b2011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith938f40b2011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith938f40b2011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Alexis Hunt913820d2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith938f40b2011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssonc80a1272009-08-25 02:29:20 +0000210bool
John McCallb268a282010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssonc80a1272009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000233 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000235
John McCallacf0ee52010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000238
Anders Carlssonc80a1272009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Douglas Gregor758cb672010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000254 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000255}
256
Chris Lattner58258242008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000260void
John McCall48871652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000264 return;
Mike Stump11289f42009-09-09 15:08:12 +0000265
John McCall48871652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlssonf1c26952009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump11289f42009-09-09 15:08:12 +0000289
John McCallb268a282010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000291}
292
Douglas Gregor58354032008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000306
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000308}
309
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump11289f42009-09-09 15:08:12 +0000315
John McCall48871652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Anders Carlsson84613c42009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Anders Carlsson84613c42009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000321}
322
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner199abbc2008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner199abbc2008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregorc732aba2009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000388
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
Francois Pichet0706d202011-09-17 17:15:52 +0000395 if (getLangOptions().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000409
Francois Pichet8cb243a2011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCalle61b02b2010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Alexis Huntd051b872011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregorc732aba2009-09-11 18:44:32 +0000501 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000502 }
503 }
504
Richard Smitheb3c10c2011-10-01 02:31:28 +0000505 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
506 // template has a constexpr specifier then all its declarations shall
507 // contain the constexpr specifier. [Note: An explicit specialization can
508 // differ from the template declaration with respect to the constexpr
509 // specifier. -- end note]
510 //
511 // FIXME: Don't reject changes in constexpr in explicit specializations.
512 if (New->isConstexpr() != Old->isConstexpr()) {
513 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
514 << New << New->isConstexpr();
515 Diag(Old->getLocation(), diag::note_previous_declaration);
516 Invalid = true;
517 }
518
Douglas Gregorf40863c2010-02-12 07:32:17 +0000519 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000520 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000521
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000522 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000523}
524
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000525/// \brief Merge the exception specifications of two variable declarations.
526///
527/// This is called when there's a redeclaration of a VarDecl. The function
528/// checks if the redeclaration might have an exception specification and
529/// validates compatibility and merges the specs if necessary.
530void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
531 // Shortcut if exceptions are disabled.
532 if (!getLangOptions().CXXExceptions)
533 return;
534
535 assert(Context.hasSameType(New->getType(), Old->getType()) &&
536 "Should only be called if types are otherwise the same.");
537
538 QualType NewType = New->getType();
539 QualType OldType = Old->getType();
540
541 // We're only interested in pointers and references to functions, as well
542 // as pointers to member functions.
543 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
544 NewType = R->getPointeeType();
545 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
546 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
547 NewType = P->getPointeeType();
548 OldType = OldType->getAs<PointerType>()->getPointeeType();
549 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
550 NewType = M->getPointeeType();
551 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
552 }
553
554 if (!NewType->isFunctionProtoType())
555 return;
556
557 // There's lots of special cases for functions. For function pointers, system
558 // libraries are hopefully not as broken so that we don't need these
559 // workarounds.
560 if (CheckEquivalentExceptionSpec(
561 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
562 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
563 New->setInvalidDecl();
564 }
565}
566
Chris Lattner199abbc2008-04-08 05:04:30 +0000567/// CheckCXXDefaultArguments - Verify that the default arguments for a
568/// function declaration are well-formed according to C++
569/// [dcl.fct.default].
570void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
571 unsigned NumParams = FD->getNumParams();
572 unsigned p;
573
574 // Find first parameter with a default argument
575 for (p = 0; p < NumParams; ++p) {
576 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000577 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000578 break;
579 }
580
581 // C++ [dcl.fct.default]p4:
582 // In a given function declaration, all parameters
583 // subsequent to a parameter with a default argument shall
584 // have default arguments supplied in this or previous
585 // declarations. A default argument shall not be redefined
586 // by a later declaration (not even to the same value).
587 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000588 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000589 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000590 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000591 if (Param->isInvalidDecl())
592 /* We already complained about this parameter. */;
593 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000594 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000595 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000596 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000597 else
Mike Stump11289f42009-09-09 15:08:12 +0000598 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000599 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner199abbc2008-04-08 05:04:30 +0000601 LastMissingDefaultArg = p;
602 }
603 }
604
605 if (LastMissingDefaultArg > 0) {
606 // Some default arguments were missing. Clear out all of the
607 // default arguments up to (and including) the last missing
608 // default argument, so that we leave the function parameters
609 // in a semantically valid state.
610 for (p = 0; p <= LastMissingDefaultArg; ++p) {
611 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000612 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000613 Param->setDefaultArg(0);
614 }
615 }
616 }
617}
Douglas Gregor556877c2008-04-13 21:30:24 +0000618
Richard Smitheb3c10c2011-10-01 02:31:28 +0000619// CheckConstexprParameterTypes - Check whether a function's parameter types
620// are all literal types. If so, return true. If not, produce a suitable
621// diagnostic depending on @p CCK and return false.
622static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
623 Sema::CheckConstexprKind CCK) {
624 unsigned ArgIndex = 0;
625 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
626 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
627 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
628 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
629 SourceLocation ParamLoc = PD->getLocation();
630 if (!(*i)->isDependentType() &&
631 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
632 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
633 << ArgIndex+1 << PD->getSourceRange()
634 << isa<CXXConstructorDecl>(FD) :
635 SemaRef.PDiag(),
636 /*AllowIncompleteType*/ true)) {
637 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
638 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
639 << ArgIndex+1 << PD->getSourceRange()
640 << isa<CXXConstructorDecl>(FD) << *i;
641 return false;
642 }
643 }
644 return true;
645}
646
647// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
648// the requirements of a constexpr function declaration or a constexpr
649// constructor declaration. Return true if it does, false if not.
650//
651// This implements C++0x [dcl.constexpr]p3,4, as amended by N3308.
652//
653// \param CCK Specifies whether to produce diagnostics if the function does not
654// satisfy the requirements.
655bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
656 CheckConstexprKind CCK) {
657 assert((CCK != CCK_NoteNonConstexprInstantiation ||
658 (NewFD->getTemplateInstantiationPattern() &&
659 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
660 "only constexpr templates can be instantiated non-constexpr");
661
662 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(NewFD)) {
663 // C++0x [dcl.constexpr]p4:
664 // In the definition of a constexpr constructor, each of the parameter
665 // types shall be a literal type.
666 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
667 return false;
668
669 // In addition, either its function-body shall be = delete or = default or
670 // it shall satisfy the following constraints:
671 // - the class shall not have any virtual base classes;
672 const CXXRecordDecl *RD = CD->getParent();
673 if (RD->getNumVBases()) {
674 // Note, this is still illegal if the body is = default, since the
675 // implicit body does not satisfy the requirements of a constexpr
676 // constructor. We also reject cases where the body is = delete, as
677 // required by N3308.
678 if (CCK != CCK_Instantiation) {
679 Diag(NewFD->getLocation(),
680 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
681 : diag::note_constexpr_tmpl_virtual_base)
682 << RD->isStruct() << RD->getNumVBases();
683 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
684 E = RD->vbases_end(); I != E; ++I)
685 Diag(I->getSourceRange().getBegin(),
686 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
687 }
688 return false;
689 }
690 } else {
691 // C++0x [dcl.constexpr]p3:
692 // The definition of a constexpr function shall satisfy the following
693 // constraints:
694 // - it shall not be virtual;
695 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
696 if (Method && Method->isVirtual()) {
697 if (CCK != CCK_Instantiation) {
698 Diag(NewFD->getLocation(),
699 CCK == CCK_Declaration ? diag::err_constexpr_virtual
700 : diag::note_constexpr_tmpl_virtual);
701
702 // If it's not obvious why this function is virtual, find an overridden
703 // function which uses the 'virtual' keyword.
704 const CXXMethodDecl *WrittenVirtual = Method;
705 while (!WrittenVirtual->isVirtualAsWritten())
706 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
707 if (WrittenVirtual != Method)
708 Diag(WrittenVirtual->getLocation(),
709 diag::note_overridden_virtual_function);
710 }
711 return false;
712 }
713
714 // - its return type shall be a literal type;
715 QualType RT = NewFD->getResultType();
716 if (!RT->isDependentType() &&
717 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
718 PDiag(diag::err_constexpr_non_literal_return) :
719 PDiag(),
720 /*AllowIncompleteType*/ true)) {
721 if (CCK == CCK_NoteNonConstexprInstantiation)
722 Diag(NewFD->getLocation(),
723 diag::note_constexpr_tmpl_non_literal_return) << RT;
724 return false;
725 }
726
727 // - each of its parameter types shall be a literal type;
728 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
729 return false;
730 }
731
732 return true;
733}
734
735/// Check the given declaration statement is legal within a constexpr function
736/// body. C++0x [dcl.constexpr]p3,p4.
737///
738/// \return true if the body is OK, false if we have diagnosed a problem.
739static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
740 DeclStmt *DS) {
741 // C++0x [dcl.constexpr]p3 and p4:
742 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
743 // contain only
744 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
745 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
746 switch ((*DclIt)->getKind()) {
747 case Decl::StaticAssert:
748 case Decl::Using:
749 case Decl::UsingShadow:
750 case Decl::UsingDirective:
751 case Decl::UnresolvedUsingTypename:
752 // - static_assert-declarations
753 // - using-declarations,
754 // - using-directives,
755 continue;
756
757 case Decl::Typedef:
758 case Decl::TypeAlias: {
759 // - typedef declarations and alias-declarations that do not define
760 // classes or enumerations,
761 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
762 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
763 // Don't allow variably-modified types in constexpr functions.
764 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
765 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
766 << TL.getSourceRange() << TL.getType()
767 << isa<CXXConstructorDecl>(Dcl);
768 return false;
769 }
770 continue;
771 }
772
773 case Decl::Enum:
774 case Decl::CXXRecord:
775 // As an extension, we allow the declaration (but not the definition) of
776 // classes and enumerations in all declarations, not just in typedef and
777 // alias declarations.
778 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
779 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
780 << isa<CXXConstructorDecl>(Dcl);
781 return false;
782 }
783 continue;
784
785 case Decl::Var:
786 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
787 << isa<CXXConstructorDecl>(Dcl);
788 return false;
789
790 default:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794 }
795 }
796
797 return true;
798}
799
800/// Check that the given field is initialized within a constexpr constructor.
801///
802/// \param Dcl The constexpr constructor being checked.
803/// \param Field The field being checked. This may be a member of an anonymous
804/// struct or union nested within the class being checked.
805/// \param Inits All declarations, including anonymous struct/union members and
806/// indirect members, for which any initialization was provided.
807/// \param Diagnosed Set to true if an error is produced.
808static void CheckConstexprCtorInitializer(Sema &SemaRef,
809 const FunctionDecl *Dcl,
810 FieldDecl *Field,
811 llvm::SmallSet<Decl*, 16> &Inits,
812 bool &Diagnosed) {
813 if (!Inits.count(Field)) {
814 if (!Diagnosed) {
815 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
816 Diagnosed = true;
817 }
818 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
819 } else if (Field->isAnonymousStructOrUnion()) {
820 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
821 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
822 I != E; ++I)
823 // If an anonymous union contains an anonymous struct of which any member
824 // is initialized, all members must be initialized.
825 if (!RD->isUnion() || Inits.count(*I))
826 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
827 }
828}
829
830/// Check the body for the given constexpr function declaration only contains
831/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
832///
833/// \return true if the body is OK, false if we have diagnosed a problem.
834bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
835 if (isa<CXXTryStmt>(Body)) {
836 // C++0x [dcl.constexpr]p3:
837 // The definition of a constexpr function shall satisfy the following
838 // constraints: [...]
839 // - its function-body shall be = delete, = default, or a
840 // compound-statement
841 //
842 // C++0x [dcl.constexpr]p4:
843 // In the definition of a constexpr constructor, [...]
844 // - its function-body shall not be a function-try-block;
845 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
846 << isa<CXXConstructorDecl>(Dcl);
847 return false;
848 }
849
850 // - its function-body shall be [...] a compound-statement that contains only
851 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
852
853 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
854 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
855 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
856 switch ((*BodyIt)->getStmtClass()) {
857 case Stmt::NullStmtClass:
858 // - null statements,
859 continue;
860
861 case Stmt::DeclStmtClass:
862 // - static_assert-declarations
863 // - using-declarations,
864 // - using-directives,
865 // - typedef declarations and alias-declarations that do not define
866 // classes or enumerations,
867 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
868 return false;
869 continue;
870
871 case Stmt::ReturnStmtClass:
872 // - and exactly one return statement;
873 if (isa<CXXConstructorDecl>(Dcl))
874 break;
875
876 ReturnStmts.push_back((*BodyIt)->getLocStart());
877 // FIXME
878 // - every constructor call and implicit conversion used in initializing
879 // the return value shall be one of those allowed in a constant
880 // expression.
881 // Deal with this as part of a general check that the function can produce
882 // a constant expression (for [dcl.constexpr]p5).
883 continue;
884
885 default:
886 break;
887 }
888
889 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 if (const CXXConstructorDecl *Constructor
895 = dyn_cast<CXXConstructorDecl>(Dcl)) {
896 const CXXRecordDecl *RD = Constructor->getParent();
897 // - every non-static data member and base class sub-object shall be
898 // initialized;
899 if (RD->isUnion()) {
900 // DR1359: Exactly one member of a union shall be initialized.
901 if (Constructor->getNumCtorInitializers() == 0) {
902 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
903 return false;
904 }
Richard Smithf368fb42011-10-10 16:38:04 +0000905 } else if (!Constructor->isDependentContext() &&
906 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000907 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
908
909 // Skip detailed checking if we have enough initializers, and we would
910 // allow at most one initializer per member.
911 bool AnyAnonStructUnionMembers = false;
912 unsigned Fields = 0;
913 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
914 E = RD->field_end(); I != E; ++I, ++Fields) {
915 if ((*I)->isAnonymousStructOrUnion()) {
916 AnyAnonStructUnionMembers = true;
917 break;
918 }
919 }
920 if (AnyAnonStructUnionMembers ||
921 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
922 // Check initialization of non-static data members. Base classes are
923 // always initialized so do not need to be checked. Dependent bases
924 // might not have initializers in the member initializer list.
925 llvm::SmallSet<Decl*, 16> Inits;
926 for (CXXConstructorDecl::init_const_iterator
927 I = Constructor->init_begin(), E = Constructor->init_end();
928 I != E; ++I) {
929 if (FieldDecl *FD = (*I)->getMember())
930 Inits.insert(FD);
931 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
932 Inits.insert(ID->chain_begin(), ID->chain_end());
933 }
934
935 bool Diagnosed = false;
936 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
937 E = RD->field_end(); I != E; ++I)
938 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
939 if (Diagnosed)
940 return false;
941 }
942 }
943
944 // FIXME
945 // - every constructor involved in initializing non-static data members
946 // and base class sub-objects shall be a constexpr constructor;
947 // - every assignment-expression that is an initializer-clause appearing
948 // directly or indirectly within a brace-or-equal-initializer for
949 // a non-static data member that is not named by a mem-initializer-id
950 // shall be a constant expression; and
951 // - every implicit conversion used in converting a constructor argument
952 // to the corresponding parameter type and converting
953 // a full-expression to the corresponding member type shall be one of
954 // those allowed in a constant expression.
955 // Deal with these as part of a general check that the function can produce
956 // a constant expression (for [dcl.constexpr]p5).
957 } else {
958 if (ReturnStmts.empty()) {
959 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
960 return false;
961 }
962 if (ReturnStmts.size() > 1) {
963 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
964 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
965 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
966 return false;
967 }
968 }
969
970 return true;
971}
972
Douglas Gregor61956c42008-10-31 09:07:45 +0000973/// isCurrentClassName - Determine whether the identifier II is the
974/// name of the class type currently being defined. In the case of
975/// nested classes, this will only return true if II is the name of
976/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000977bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
978 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000979 assert(getLangOptions().CPlusPlus && "No class names in C!");
980
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000981 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000982 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000983 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000984 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
985 } else
986 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
987
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000988 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000989 return &II == CurDecl->getIdentifier();
990 else
991 return false;
992}
993
Mike Stump11289f42009-09-09 15:08:12 +0000994/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000995///
996/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
997/// and returns NULL otherwise.
998CXXBaseSpecifier *
999Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1000 SourceRange SpecifierRange,
1001 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001002 TypeSourceInfo *TInfo,
1003 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001004 QualType BaseType = TInfo->getType();
1005
Douglas Gregor463421d2009-03-03 04:44:36 +00001006 // C++ [class.union]p1:
1007 // A union shall not have base classes.
1008 if (Class->isUnion()) {
1009 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1010 << SpecifierRange;
1011 return 0;
1012 }
1013
Douglas Gregor752a5952011-01-03 22:36:02 +00001014 if (EllipsisLoc.isValid() &&
1015 !TInfo->getType()->containsUnexpandedParameterPack()) {
1016 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1017 << TInfo->getTypeLoc().getSourceRange();
1018 EllipsisLoc = SourceLocation();
1019 }
1020
Douglas Gregor463421d2009-03-03 04:44:36 +00001021 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +00001022 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001023 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001024 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001025
1026 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +00001027
1028 // Base specifiers must be record types.
1029 if (!BaseType->isRecordType()) {
1030 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1031 return 0;
1032 }
1033
1034 // C++ [class.union]p1:
1035 // A union shall not be used as a base class.
1036 if (BaseType->isUnionType()) {
1037 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1038 return 0;
1039 }
1040
1041 // C++ [class.derived]p2:
1042 // The class-name in a base-specifier shall not be an incompletely
1043 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001044 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00001045 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +00001046 << SpecifierRange)) {
1047 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001048 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001049 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001050
Eli Friedmanc96d4962009-08-15 21:55:26 +00001051 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001052 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001053 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001054 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001055 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +00001056 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1057 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001058
Anders Carlsson65c76d32011-03-25 14:55:14 +00001059 // C++ [class]p3:
1060 // If a class is marked final and it appears as a base-type-specifier in
1061 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001062 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001063 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1064 << CXXBaseDecl->getDeclName();
1065 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1066 << CXXBaseDecl->getDeclName();
1067 return 0;
1068 }
1069
John McCall3696dcb2010-08-17 07:23:57 +00001070 if (BaseDecl->isInvalidDecl())
1071 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001072
1073 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001074 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001075 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001076 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001077}
1078
Douglas Gregor556877c2008-04-13 21:30:24 +00001079/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1080/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001081/// example:
1082/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001083/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001084BaseResult
John McCall48871652010-08-21 09:40:31 +00001085Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +00001086 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001087 ParsedType basetype, SourceLocation BaseLoc,
1088 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001089 if (!classdecl)
1090 return true;
1091
Douglas Gregorc40290e2009-03-09 23:48:35 +00001092 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001093 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001094 if (!Class)
1095 return true;
1096
Nick Lewycky19b9f952010-07-26 16:56:01 +00001097 TypeSourceInfo *TInfo = 0;
1098 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001099
Douglas Gregor752a5952011-01-03 22:36:02 +00001100 if (EllipsisLoc.isInvalid() &&
1101 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001102 UPPC_BaseType))
1103 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001104
Douglas Gregor463421d2009-03-03 04:44:36 +00001105 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001106 Virtual, Access, TInfo,
1107 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001108 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +00001109
Douglas Gregor463421d2009-03-03 04:44:36 +00001110 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001111}
Douglas Gregor556877c2008-04-13 21:30:24 +00001112
Douglas Gregor463421d2009-03-03 04:44:36 +00001113/// \brief Performs the actual work of attaching the given base class
1114/// specifiers to a C++ class.
1115bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1116 unsigned NumBases) {
1117 if (NumBases == 0)
1118 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001119
1120 // Used to keep track of which base types we have already seen, so
1121 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001122 // that the key is always the unqualified canonical type of the base
1123 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001124 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1125
1126 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001127 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001128 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001129 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001130 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001131 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001132 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +00001133 if (KnownBaseTypes[NewBaseType]) {
1134 // C++ [class.mi]p3:
1135 // A class shall not be specified as a direct base class of a
1136 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +00001137 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001138 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001139 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001140 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001141
1142 // Delete the duplicate base class specifier; we're going to
1143 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001144 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001145
1146 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001147 } else {
1148 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +00001149 KnownBaseTypes[NewBaseType] = Bases[idx];
1150 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +00001151 }
1152 }
1153
1154 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001155 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001156
1157 // Delete the remaining (good) base class specifiers, since their
1158 // data has been copied into the CXXRecordDecl.
1159 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001160 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001161
1162 return Invalid;
1163}
1164
1165/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1166/// class, after checking whether there are any duplicate base
1167/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001168void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001169 unsigned NumBases) {
1170 if (!ClassDecl || !Bases || !NumBases)
1171 return;
1172
1173 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001174 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001175 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001176}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001177
John McCalle78aac42010-03-10 03:28:59 +00001178static CXXRecordDecl *GetClassForType(QualType T) {
1179 if (const RecordType *RT = T->getAs<RecordType>())
1180 return cast<CXXRecordDecl>(RT->getDecl());
1181 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1182 return ICT->getDecl();
1183 else
1184 return 0;
1185}
1186
Douglas Gregor36d1b142009-10-06 17:59:45 +00001187/// \brief Determine whether the type \p Derived is a C++ class that is
1188/// derived from the type \p Base.
1189bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1190 if (!getLangOptions().CPlusPlus)
1191 return false;
John McCalle78aac42010-03-10 03:28:59 +00001192
1193 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1194 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001195 return false;
1196
John McCalle78aac42010-03-10 03:28:59 +00001197 CXXRecordDecl *BaseRD = GetClassForType(Base);
1198 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001199 return false;
1200
John McCall67da35c2010-02-04 22:26:26 +00001201 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1202 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001203}
1204
1205/// \brief Determine whether the type \p Derived is a C++ class that is
1206/// derived from the type \p Base.
1207bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1208 if (!getLangOptions().CPlusPlus)
1209 return false;
1210
John McCalle78aac42010-03-10 03:28:59 +00001211 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1212 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001213 return false;
1214
John McCalle78aac42010-03-10 03:28:59 +00001215 CXXRecordDecl *BaseRD = GetClassForType(Base);
1216 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001217 return false;
1218
Douglas Gregor36d1b142009-10-06 17:59:45 +00001219 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1220}
1221
Anders Carlssona70cff62010-04-24 19:06:50 +00001222void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001223 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001224 assert(BasePathArray.empty() && "Base path array must be empty!");
1225 assert(Paths.isRecordingPaths() && "Must record paths!");
1226
1227 const CXXBasePath &Path = Paths.front();
1228
1229 // We first go backward and check if we have a virtual base.
1230 // FIXME: It would be better if CXXBasePath had the base specifier for
1231 // the nearest virtual base.
1232 unsigned Start = 0;
1233 for (unsigned I = Path.size(); I != 0; --I) {
1234 if (Path[I - 1].Base->isVirtual()) {
1235 Start = I - 1;
1236 break;
1237 }
1238 }
1239
1240 // Now add all bases.
1241 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001242 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001243}
1244
Douglas Gregor88d292c2010-05-13 16:44:06 +00001245/// \brief Determine whether the given base path includes a virtual
1246/// base class.
John McCallcf142162010-08-07 06:22:56 +00001247bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1248 for (CXXCastPath::const_iterator B = BasePath.begin(),
1249 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001250 B != BEnd; ++B)
1251 if ((*B)->isVirtual())
1252 return true;
1253
1254 return false;
1255}
1256
Douglas Gregor36d1b142009-10-06 17:59:45 +00001257/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1258/// conversion (where Derived and Base are class types) is
1259/// well-formed, meaning that the conversion is unambiguous (and
1260/// that all of the base classes are accessible). Returns true
1261/// and emits a diagnostic if the code is ill-formed, returns false
1262/// otherwise. Loc is the location where this routine should point to
1263/// if there is an error, and Range is the source range to highlight
1264/// if there is an error.
1265bool
1266Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001267 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001268 unsigned AmbigiousBaseConvID,
1269 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001270 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001271 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001272 // First, determine whether the path from Derived to Base is
1273 // ambiguous. This is slightly more expensive than checking whether
1274 // the Derived to Base conversion exists, because here we need to
1275 // explore multiple paths to determine if there is an ambiguity.
1276 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1277 /*DetectVirtual=*/false);
1278 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1279 assert(DerivationOkay &&
1280 "Can only be used with a derived-to-base conversion");
1281 (void)DerivationOkay;
1282
1283 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001284 if (InaccessibleBaseID) {
1285 // Check that the base class can be accessed.
1286 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1287 InaccessibleBaseID)) {
1288 case AR_inaccessible:
1289 return true;
1290 case AR_accessible:
1291 case AR_dependent:
1292 case AR_delayed:
1293 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001294 }
John McCall5b0829a2010-02-10 09:31:12 +00001295 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001296
1297 // Build a base path if necessary.
1298 if (BasePath)
1299 BuildBasePathArray(Paths, *BasePath);
1300 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001301 }
1302
1303 // We know that the derived-to-base conversion is ambiguous, and
1304 // we're going to produce a diagnostic. Perform the derived-to-base
1305 // search just one more time to compute all of the possible paths so
1306 // that we can print them out. This is more expensive than any of
1307 // the previous derived-to-base checks we've done, but at this point
1308 // performance isn't as much of an issue.
1309 Paths.clear();
1310 Paths.setRecordingPaths(true);
1311 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1312 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1313 (void)StillOkay;
1314
1315 // Build up a textual representation of the ambiguous paths, e.g.,
1316 // D -> B -> A, that will be used to illustrate the ambiguous
1317 // conversions in the diagnostic. We only print one of the paths
1318 // to each base class subobject.
1319 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1320
1321 Diag(Loc, AmbigiousBaseConvID)
1322 << Derived << Base << PathDisplayStr << Range << Name;
1323 return true;
1324}
1325
1326bool
1327Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001328 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001329 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001330 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001331 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001332 IgnoreAccess ? 0
1333 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001334 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001335 Loc, Range, DeclarationName(),
1336 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001337}
1338
1339
1340/// @brief Builds a string representing ambiguous paths from a
1341/// specific derived class to different subobjects of the same base
1342/// class.
1343///
1344/// This function builds a string that can be used in error messages
1345/// to show the different paths that one can take through the
1346/// inheritance hierarchy to go from the derived class to different
1347/// subobjects of a base class. The result looks something like this:
1348/// @code
1349/// struct D -> struct B -> struct A
1350/// struct D -> struct C -> struct A
1351/// @endcode
1352std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1353 std::string PathDisplayStr;
1354 std::set<unsigned> DisplayedPaths;
1355 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1356 Path != Paths.end(); ++Path) {
1357 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1358 // We haven't displayed a path to this particular base
1359 // class subobject yet.
1360 PathDisplayStr += "\n ";
1361 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1362 for (CXXBasePath::const_iterator Element = Path->begin();
1363 Element != Path->end(); ++Element)
1364 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1365 }
1366 }
1367
1368 return PathDisplayStr;
1369}
1370
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001371//===----------------------------------------------------------------------===//
1372// C++ class member Handling
1373//===----------------------------------------------------------------------===//
1374
Abramo Bagnarad7340582010-06-05 05:09:32 +00001375/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +00001376Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1377 SourceLocation ASLoc,
1378 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001379 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001380 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001381 ASLoc, ColonLoc);
1382 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +00001383 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +00001384}
1385
Anders Carlssonfd835532011-01-20 05:57:14 +00001386/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001387void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001388 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001389 if (!MD || !MD->isVirtual())
1390 return;
1391
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001392 if (MD->isDependentContext())
1393 return;
1394
Anders Carlssonfd835532011-01-20 05:57:14 +00001395 // C++0x [class.virtual]p3:
1396 // If a virtual function is marked with the virt-specifier override and does
1397 // not override a member function of a base class,
1398 // the program is ill-formed.
1399 bool HasOverriddenMethods =
1400 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001401 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001402 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001403 diag::err_function_marked_override_not_overriding)
1404 << MD->getDeclName();
1405 return;
1406 }
1407}
1408
Anders Carlsson3f610c72011-01-20 16:25:36 +00001409/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1410/// function overrides a virtual member function marked 'final', according to
1411/// C++0x [class.virtual]p3.
1412bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1413 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001414 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001415 return false;
1416
1417 Diag(New->getLocation(), diag::err_final_function_overridden)
1418 << New->getDeclName();
1419 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1420 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001421}
1422
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001423/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1424/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001425/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1426/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1427/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001428Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001429Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001430 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001431 Expr *BW, const VirtSpecifiers &VS,
Douglas Gregor728d00b2011-10-10 14:49:18 +00001432 bool HasDeferredInit,
Richard Smith938f40b2011-06-11 17:19:42 +00001433 bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001434 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001435 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1436 DeclarationName Name = NameInfo.getName();
1437 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001438
1439 // For anonymous bitfields, the location should point to the type.
1440 if (Loc.isInvalid())
1441 Loc = D.getSourceRange().getBegin();
1442
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001443 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001444
John McCallb1cd7da2010-06-04 08:34:12 +00001445 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001446 assert(!DS.isFriendSpecified());
1447
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001448 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001449
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001450 // C++ 9.2p6: A member shall not be declared to have automatic storage
1451 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001452 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1453 // data members and cannot be applied to names declared const or static,
1454 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001455 switch (DS.getStorageClassSpec()) {
1456 case DeclSpec::SCS_unspecified:
1457 case DeclSpec::SCS_typedef:
1458 case DeclSpec::SCS_static:
1459 // FALL THROUGH.
1460 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001461 case DeclSpec::SCS_mutable:
1462 if (isFunc) {
1463 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001464 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001465 else
Chris Lattner3b054132008-11-19 05:08:23 +00001466 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001467
Sebastian Redl8071edb2008-11-17 23:24:37 +00001468 // FIXME: It would be nicer if the keyword was ignored only for this
1469 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001470 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001471 }
1472 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001473 default:
1474 if (DS.getStorageClassSpecLoc().isValid())
1475 Diag(DS.getStorageClassSpecLoc(),
1476 diag::err_storageclass_invalid_for_member);
1477 else
1478 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1479 D.getMutableDeclSpec().ClearStorageClassSpecs();
1480 }
1481
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001482 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1483 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001484 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001485
1486 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001487 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001488 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001489
1490 // Data members must have identifiers for names.
1491 if (Name.getNameKind() != DeclarationName::Identifier) {
1492 Diag(Loc, diag::err_bad_variable_name)
1493 << Name;
1494 return 0;
1495 }
Douglas Gregora007d362010-10-13 22:19:53 +00001496
Douglas Gregor7c26c042011-09-21 14:40:46 +00001497 IdentifierInfo *II = Name.getAsIdentifierInfo();
1498
1499 // Member field could not be with "template" keyword.
1500 // So TemplateParameterLists should be empty in this case.
1501 if (TemplateParameterLists.size()) {
1502 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1503 if (TemplateParams->size()) {
1504 // There is no such thing as a member field template.
1505 Diag(D.getIdentifierLoc(), diag::err_template_member)
1506 << II
1507 << SourceRange(TemplateParams->getTemplateLoc(),
1508 TemplateParams->getRAngleLoc());
1509 } else {
1510 // There is an extraneous 'template<>' for this member.
1511 Diag(TemplateParams->getTemplateLoc(),
1512 diag::err_template_member_noparams)
1513 << II
1514 << SourceRange(TemplateParams->getTemplateLoc(),
1515 TemplateParams->getRAngleLoc());
1516 }
1517 return 0;
1518 }
1519
Douglas Gregora007d362010-10-13 22:19:53 +00001520 if (SS.isSet() && !SS.isInvalid()) {
1521 // The user provided a superfluous scope specifier inside a class
1522 // definition:
1523 //
1524 // class X {
1525 // int X::member;
1526 // };
1527 DeclContext *DC = 0;
1528 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1529 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1530 << Name << FixItHint::CreateRemoval(SS.getRange());
1531 else
1532 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1533 << Name << SS.getRange();
1534
1535 SS.clear();
1536 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001537
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001538 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001539 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001540 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001541 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001542 assert(!HasDeferredInit);
1543
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001544 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001545 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001546 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001547 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001548
1549 // Non-instance-fields can't have a bitfield.
1550 if (BitWidth) {
1551 if (Member->isInvalidDecl()) {
1552 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001553 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001554 // C++ 9.6p3: A bit-field shall not be a static member.
1555 // "static member 'A' cannot be a bit-field"
1556 Diag(Loc, diag::err_static_not_bitfield)
1557 << Name << BitWidth->getSourceRange();
1558 } else if (isa<TypedefDecl>(Member)) {
1559 // "typedef member 'x' cannot be a bit-field"
1560 Diag(Loc, diag::err_typedef_not_bitfield)
1561 << Name << BitWidth->getSourceRange();
1562 } else {
1563 // A function typedef ("typedef int f(); f a;").
1564 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1565 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001566 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001567 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
Chris Lattnerd26760a2009-03-05 23:01:03 +00001570 BitWidth = 0;
1571 Member->setInvalidDecl();
1572 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001573
1574 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Douglas Gregor3447e762009-08-20 22:52:58 +00001576 // If we have declared a member function template, set the access of the
1577 // templated declaration as well.
1578 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1579 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001580 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001581
Anders Carlsson13a69102011-01-20 04:34:22 +00001582 if (VS.isOverrideSpecified()) {
1583 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1584 if (!MD || !MD->isVirtual()) {
1585 Diag(Member->getLocStart(),
1586 diag::override_keyword_only_allowed_on_virtual_member_functions)
1587 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001588 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001589 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001590 }
1591 if (VS.isFinalSpecified()) {
1592 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1593 if (!MD || !MD->isVirtual()) {
1594 Diag(Member->getLocStart(),
1595 diag::override_keyword_only_allowed_on_virtual_member_functions)
1596 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001597 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001598 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001599 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001600
Douglas Gregorf2f08062011-03-08 17:10:18 +00001601 if (VS.getLastLocation().isValid()) {
1602 // Update the end location of a method that has a virt-specifiers.
1603 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1604 MD->setRangeEnd(VS.getLastLocation());
1605 }
1606
Anders Carlssonc87f8612011-01-20 06:29:02 +00001607 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001608
Douglas Gregor92751d42008-11-17 22:58:34 +00001609 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001610
John McCall25849ca2011-02-15 07:12:36 +00001611 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001612 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001613 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001614}
1615
Richard Smith938f40b2011-06-11 17:19:42 +00001616/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001617/// in-class initializer for a non-static C++ class member, and after
1618/// instantiating an in-class initializer in a class template. Such actions
1619/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001620void
1621Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1622 Expr *InitExpr) {
1623 FieldDecl *FD = cast<FieldDecl>(D);
1624
1625 if (!InitExpr) {
1626 FD->setInvalidDecl();
1627 FD->removeInClassInitializer();
1628 return;
1629 }
1630
1631 ExprResult Init = InitExpr;
1632 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1633 // FIXME: if there is no EqualLoc, this is list-initialization.
1634 Init = PerformCopyInitialization(
1635 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1636 if (Init.isInvalid()) {
1637 FD->setInvalidDecl();
1638 return;
1639 }
1640
1641 CheckImplicitConversions(Init.get(), EqualLoc);
1642 }
1643
1644 // C++0x [class.base.init]p7:
1645 // The initialization of each base and member constitutes a
1646 // full-expression.
1647 Init = MaybeCreateExprWithCleanups(Init);
1648 if (Init.isInvalid()) {
1649 FD->setInvalidDecl();
1650 return;
1651 }
1652
1653 InitExpr = Init.release();
1654
1655 FD->setInClassInitializer(InitExpr);
1656}
1657
Douglas Gregor15e77a22009-12-31 09:10:24 +00001658/// \brief Find the direct and/or virtual base specifiers that
1659/// correspond to the given base type, for use in base initialization
1660/// within a constructor.
1661static bool FindBaseInitializer(Sema &SemaRef,
1662 CXXRecordDecl *ClassDecl,
1663 QualType BaseType,
1664 const CXXBaseSpecifier *&DirectBaseSpec,
1665 const CXXBaseSpecifier *&VirtualBaseSpec) {
1666 // First, check for a direct base class.
1667 DirectBaseSpec = 0;
1668 for (CXXRecordDecl::base_class_const_iterator Base
1669 = ClassDecl->bases_begin();
1670 Base != ClassDecl->bases_end(); ++Base) {
1671 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1672 // We found a direct base of this type. That's what we're
1673 // initializing.
1674 DirectBaseSpec = &*Base;
1675 break;
1676 }
1677 }
1678
1679 // Check for a virtual base class.
1680 // FIXME: We might be able to short-circuit this if we know in advance that
1681 // there are no virtual bases.
1682 VirtualBaseSpec = 0;
1683 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1684 // We haven't found a base yet; search the class hierarchy for a
1685 // virtual base class.
1686 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1687 /*DetectVirtual=*/false);
1688 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1689 BaseType, Paths)) {
1690 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1691 Path != Paths.end(); ++Path) {
1692 if (Path->back().Base->isVirtual()) {
1693 VirtualBaseSpec = Path->back().Base;
1694 break;
1695 }
1696 }
1697 }
1698 }
1699
1700 return DirectBaseSpec || VirtualBaseSpec;
1701}
1702
Sebastian Redla74948d2011-09-24 17:48:25 +00001703/// \brief Handle a C++ member initializer using braced-init-list syntax.
1704MemInitResult
1705Sema::ActOnMemInitializer(Decl *ConstructorD,
1706 Scope *S,
1707 CXXScopeSpec &SS,
1708 IdentifierInfo *MemberOrBase,
1709 ParsedType TemplateTypeTy,
1710 SourceLocation IdLoc,
1711 Expr *InitList,
1712 SourceLocation EllipsisLoc) {
1713 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1714 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1715}
1716
1717/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001718MemInitResult
John McCall48871652010-08-21 09:40:31 +00001719Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001720 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001721 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001722 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001723 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001724 SourceLocation IdLoc,
1725 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001726 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001727 SourceLocation RParenLoc,
1728 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001729 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1730 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1731 RParenLoc),
1732 EllipsisLoc);
1733}
1734
1735/// \brief Handle a C++ member initializer.
1736MemInitResult
1737Sema::BuildMemInitializer(Decl *ConstructorD,
1738 Scope *S,
1739 CXXScopeSpec &SS,
1740 IdentifierInfo *MemberOrBase,
1741 ParsedType TemplateTypeTy,
1742 SourceLocation IdLoc,
1743 const MultiInitializer &Args,
1744 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001745 if (!ConstructorD)
1746 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001747
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001748 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001749
1750 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001751 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001752 if (!Constructor) {
1753 // The user wrote a constructor initializer on a function that is
1754 // not a C++ constructor. Ignore the error for now, because we may
1755 // have more member initializers coming; we'll diagnose it just
1756 // once in ActOnMemInitializers.
1757 return true;
1758 }
1759
1760 CXXRecordDecl *ClassDecl = Constructor->getParent();
1761
1762 // C++ [class.base.init]p2:
1763 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001764 // constructor's class and, if not found in that scope, are looked
1765 // up in the scope containing the constructor's definition.
1766 // [Note: if the constructor's class contains a member with the
1767 // same name as a direct or virtual base class of the class, a
1768 // mem-initializer-id naming the member or base class and composed
1769 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001770 // mem-initializer-id for the hidden base class may be specified
1771 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001772 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001773 // Look for a member, first.
1774 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001775 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001776 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001777 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001778 Member = dyn_cast<FieldDecl>(*Result.first);
Sebastian Redla74948d2011-09-24 17:48:25 +00001779
Douglas Gregor44e7df62011-01-04 00:32:56 +00001780 if (Member) {
1781 if (EllipsisLoc.isValid())
1782 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001783 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1784
1785 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001786 }
Sebastian Redla74948d2011-09-24 17:48:25 +00001787
Francois Pichetd583da02010-12-04 09:14:42 +00001788 // Handle anonymous union case.
1789 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001790 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1791 if (EllipsisLoc.isValid())
1792 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001793 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor44e7df62011-01-04 00:32:56 +00001794
Sebastian Redla74948d2011-09-24 17:48:25 +00001795 return BuildMemberInitializer(IndirectField, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001796 }
Francois Pichetd583da02010-12-04 09:14:42 +00001797 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001798 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001799 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001800 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001801 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001802
1803 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001804 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001805 } else {
1806 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1807 LookupParsedName(R, S, &SS);
1808
1809 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1810 if (!TyD) {
1811 if (R.isAmbiguous()) return true;
1812
John McCallda6841b2010-04-09 19:01:14 +00001813 // We don't want access-control diagnostics here.
1814 R.suppressDiagnostics();
1815
Douglas Gregora3b624a2010-01-19 06:46:48 +00001816 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1817 bool NotUnknownSpecialization = false;
1818 DeclContext *DC = computeDeclContext(SS, false);
1819 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1820 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1821
1822 if (!NotUnknownSpecialization) {
1823 // When the scope specifier can refer to a member of an unknown
1824 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001825 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1826 SS.getWithLocInContext(Context),
1827 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001828 if (BaseType.isNull())
1829 return true;
1830
Douglas Gregora3b624a2010-01-19 06:46:48 +00001831 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001832 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001833 }
1834 }
1835
Douglas Gregor15e77a22009-12-31 09:10:24 +00001836 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001837 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00001838 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001839 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1840 ClassDecl, false, CTC_NoKeywords))) {
1841 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1842 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1843 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001844 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001845 // We have found a non-static data member with a similar
1846 // name to what was typed; complain and initialize that
1847 // member.
1848 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001849 << MemberOrBase << true << CorrectedQuotedStr
1850 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor6da83622010-01-07 00:17:44 +00001851 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001852 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001853
Sebastian Redla74948d2011-09-24 17:48:25 +00001854 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor15e77a22009-12-31 09:10:24 +00001855 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001856 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001857 const CXXBaseSpecifier *DirectBaseSpec;
1858 const CXXBaseSpecifier *VirtualBaseSpec;
1859 if (FindBaseInitializer(*this, ClassDecl,
1860 Context.getTypeDeclType(Type),
1861 DirectBaseSpec, VirtualBaseSpec)) {
1862 // We have found a direct or virtual base class with a
1863 // similar name to what was typed; complain and initialize
1864 // that base class.
1865 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001866 << MemberOrBase << false << CorrectedQuotedStr
1867 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001868
1869 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1870 : VirtualBaseSpec;
1871 Diag(BaseSpec->getSourceRange().getBegin(),
1872 diag::note_base_class_specified_here)
1873 << BaseSpec->getType()
1874 << BaseSpec->getSourceRange();
1875
Douglas Gregor15e77a22009-12-31 09:10:24 +00001876 TyD = Type;
1877 }
1878 }
1879 }
1880
Douglas Gregora3b624a2010-01-19 06:46:48 +00001881 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001882 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla74948d2011-09-24 17:48:25 +00001883 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001884 return true;
1885 }
John McCallb5a0d312009-12-21 10:41:20 +00001886 }
1887
Douglas Gregora3b624a2010-01-19 06:46:48 +00001888 if (BaseType.isNull()) {
1889 BaseType = Context.getTypeDeclType(TyD);
1890 if (SS.isSet()) {
1891 NestedNameSpecifier *Qualifier =
1892 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001893
Douglas Gregora3b624a2010-01-19 06:46:48 +00001894 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001895 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001896 }
John McCallb5a0d312009-12-21 10:41:20 +00001897 }
1898 }
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCallbcd03502009-12-07 02:54:59 +00001900 if (!TInfo)
1901 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001902
Sebastian Redla74948d2011-09-24 17:48:25 +00001903 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001904}
1905
Chandler Carruth599deef2011-09-03 01:14:15 +00001906/// Checks a member initializer expression for cases where reference (or
1907/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001908static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1909 Expr *Init,
1910 SourceLocation IdLoc) {
1911 QualType MemberTy = Member->getType();
1912
1913 // We only handle pointers and references currently.
1914 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1915 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1916 return;
1917
1918 const bool IsPointer = MemberTy->isPointerType();
1919 if (IsPointer) {
1920 if (const UnaryOperator *Op
1921 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1922 // The only case we're worried about with pointers requires taking the
1923 // address.
1924 if (Op->getOpcode() != UO_AddrOf)
1925 return;
1926
1927 Init = Op->getSubExpr();
1928 } else {
1929 // We only handle address-of expression initializers for pointers.
1930 return;
1931 }
1932 }
1933
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001934 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1935 // Taking the address of a temporary will be diagnosed as a hard error.
1936 if (IsPointer)
1937 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001938
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001939 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1940 << Member << Init->getSourceRange();
1941 } else if (const DeclRefExpr *DRE
1942 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1943 // We only warn when referring to a non-reference parameter declaration.
1944 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1945 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00001946 return;
1947
1948 S.Diag(Init->getExprLoc(),
1949 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1950 : diag::warn_bind_ref_member_to_parameter)
1951 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001952 } else {
1953 // Other initializers are fine.
1954 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001955 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001956
1957 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1958 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00001959}
1960
John McCalle22a04a2009-11-04 23:02:40 +00001961/// Checks an initializer expression for use of uninitialized fields, such as
1962/// containing the field that is being initialized. Returns true if there is an
1963/// uninitialized field was used an updates the SourceLocation parameter; false
1964/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001965static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001966 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001967 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001968 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1969
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001970 if (isa<CallExpr>(S)) {
1971 // Do not descend into function calls or constructors, as the use
1972 // of an uninitialized field may be valid. One would have to inspect
1973 // the contents of the function/ctor to determine if it is safe or not.
1974 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1975 // may be safe, depending on what the function/ctor does.
1976 return false;
1977 }
1978 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1979 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001980
1981 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1982 // The member expression points to a static data member.
1983 assert(VD->isStaticDataMember() &&
1984 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001985 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001986 return false;
1987 }
1988
1989 if (isa<EnumConstantDecl>(RhsField)) {
1990 // The member expression points to an enum.
1991 return false;
1992 }
1993
John McCalle22a04a2009-11-04 23:02:40 +00001994 if (RhsField == LhsField) {
1995 // Initializing a field with itself. Throw a warning.
1996 // But wait; there are exceptions!
1997 // Exception #1: The field may not belong to this record.
1998 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001999 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00002000 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2001 // Even though the field matches, it does not belong to this record.
2002 return false;
2003 }
2004 // None of the exceptions triggered; return true to indicate an
2005 // uninitialized field was used.
2006 *L = ME->getMemberLoc();
2007 return true;
2008 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002009 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00002010 // sizeof/alignof doesn't reference contents, do not warn.
2011 return false;
2012 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2013 // address-of doesn't reference contents (the pointer may be dereferenced
2014 // in the same expression but it would be rare; and weird).
2015 if (UOE->getOpcode() == UO_AddrOf)
2016 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002017 }
John McCall8322c3a2011-02-13 04:07:26 +00002018 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002019 if (!*it) {
2020 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00002021 continue;
2022 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002023 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2024 return true;
John McCalle22a04a2009-11-04 23:02:40 +00002025 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002026 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002027}
2028
John McCallfaf5fb42010-08-26 23:41:50 +00002029MemInitResult
Sebastian Redla74948d2011-09-24 17:48:25 +00002030Sema::BuildMemberInitializer(ValueDecl *Member,
2031 const MultiInitializer &Args,
2032 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002033 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2034 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2035 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002036 "Member must be a FieldDecl or IndirectFieldDecl");
2037
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002038 if (Member->isInvalidDecl())
2039 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002040
John McCalle22a04a2009-11-04 23:02:40 +00002041 // Diagnose value-uses of fields to initialize themselves, e.g.
2042 // foo(foo)
2043 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002044 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla74948d2011-09-24 17:48:25 +00002045 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2046 I != E; ++I) {
John McCalle22a04a2009-11-04 23:02:40 +00002047 SourceLocation L;
Sebastian Redla74948d2011-09-24 17:48:25 +00002048 Expr *Arg = *I;
2049 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2050 Arg = DIE->getInit();
2051 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00002052 // FIXME: Return true in the case when other fields are used before being
2053 // uninitialized. For example, let this field be the i'th field. When
2054 // initializing the i'th field, throw a warning if any of the >= i'th
2055 // fields are used, as they are not yet initialized.
2056 // Right now we are only handling the case where the i'th field uses
2057 // itself in its initializer.
2058 Diag(L, diag::warn_field_is_uninit);
2059 }
2060 }
2061
Sebastian Redla74948d2011-09-24 17:48:25 +00002062 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002063
Chandler Carruthd44c3102010-12-06 09:23:57 +00002064 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00002065 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002066 // Can't check initialization for a member of dependent type or when
2067 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002068 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002069
John McCall31168b02011-06-15 23:02:42 +00002070 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002071 } else {
2072 // Initialize the member.
2073 InitializedEntity MemberEntity =
2074 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2075 : InitializedEntity::InitializeMember(IndirectMember, 0);
2076 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002077 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2078 Args.getEndLoc());
John McCallacf0ee52010-10-08 02:01:28 +00002079
Sebastian Redla74948d2011-09-24 17:48:25 +00002080 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002081 if (MemberInit.isInvalid())
2082 return true;
2083
Sebastian Redla74948d2011-09-24 17:48:25 +00002084 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002085
2086 // C++0x [class.base.init]p7:
2087 // The initialization of each base and member constitutes a
2088 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002089 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002090 if (MemberInit.isInvalid())
2091 return true;
2092
2093 // If we are in a dependent context, template instantiation will
2094 // perform this type-checking again. Just save the arguments that we
2095 // received in a ParenListExpr.
2096 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2097 // of the information that we have about the member
2098 // initializer. However, deconstructing the ASTs is a dicey process,
2099 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00002100 if (CurContext->isDependentContext()) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002101 Init = Args.CreateInitExpr(Context,
2102 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00002103 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002104 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00002105 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2106 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002107 }
2108
Chandler Carruthd44c3102010-12-06 09:23:57 +00002109 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002110 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002111 IdLoc, Args.getStartLoc(),
2112 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002113 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00002114 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002115 IdLoc, Args.getStartLoc(),
2116 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002117 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002118}
2119
John McCallfaf5fb42010-08-26 23:41:50 +00002120MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002121Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002122 const MultiInitializer &Args,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002123 SourceLocation NameLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002124 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002125 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2126 if (!LangOpts.CPlusPlus0x)
2127 return Diag(Loc, diag::err_delegation_0x_only)
2128 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002129
Alexis Huntc5575cc2011-02-26 19:13:13 +00002130 // Initialize the object.
2131 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2132 QualType(ClassDecl->getTypeForDecl(), 0));
2133 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002134 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2135 Args.getEndLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002136
Sebastian Redla74948d2011-09-24 17:48:25 +00002137 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002138 if (DelegationInit.isInvalid())
2139 return true;
2140
2141 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00002142 CXXConstructorDecl *Constructor
2143 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002144 assert(Constructor && "Delegating constructor with no target?");
2145
Sebastian Redla74948d2011-09-24 17:48:25 +00002146 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002147
2148 // C++0x [class.base.init]p7:
2149 // The initialization of each base and member constitutes a
2150 // full-expression.
2151 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2152 if (DelegationInit.isInvalid())
2153 return true;
2154
Manuel Klimekf2b4b692011-06-22 20:02:16 +00002155 assert(!CurContext->isDependentContext());
Sebastian Redla74948d2011-09-24 17:48:25 +00002156 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
2157 Constructor,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002158 DelegationInit.takeAs<Expr>(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002159 Args.getEndLoc());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002160}
2161
2162MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002163Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002164 const MultiInitializer &Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002165 CXXRecordDecl *ClassDecl,
2166 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002167 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002168
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002169 SourceLocation BaseLoc
2170 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002171
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002172 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2173 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2174 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2175
2176 // C++ [class.base.init]p2:
2177 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002178 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002179 // of that class, the mem-initializer is ill-formed. A
2180 // mem-initializer-list can initialize a base class using any
2181 // name that denotes that base class type.
2182 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2183
Douglas Gregor44e7df62011-01-04 00:32:56 +00002184 if (EllipsisLoc.isValid()) {
2185 // This is a pack expansion.
2186 if (!BaseType->containsUnexpandedParameterPack()) {
2187 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla74948d2011-09-24 17:48:25 +00002188 << SourceRange(BaseLoc, Args.getEndLoc());
2189
Douglas Gregor44e7df62011-01-04 00:32:56 +00002190 EllipsisLoc = SourceLocation();
2191 }
2192 } else {
2193 // Check for any unexpanded parameter packs.
2194 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2195 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002196
2197 if (Args.DiagnoseUnexpandedParameterPack(*this))
2198 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002199 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002200
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002201 // Check for direct and virtual base classes.
2202 const CXXBaseSpecifier *DirectBaseSpec = 0;
2203 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2204 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002205 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2206 BaseType))
Sebastian Redla74948d2011-09-24 17:48:25 +00002207 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002208
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002209 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2210 VirtualBaseSpec);
2211
2212 // C++ [base.class.init]p2:
2213 // Unless the mem-initializer-id names a nonstatic data member of the
2214 // constructor's class or a direct or virtual base of that class, the
2215 // mem-initializer is ill-formed.
2216 if (!DirectBaseSpec && !VirtualBaseSpec) {
2217 // If the class has any dependent bases, then it's possible that
2218 // one of those types will resolve to the same type as
2219 // BaseType. Therefore, just treat this as a dependent base
2220 // class initialization. FIXME: Should we try to check the
2221 // initialization anyway? It seems odd.
2222 if (ClassDecl->hasAnyDependentBases())
2223 Dependent = true;
2224 else
2225 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2226 << BaseType << Context.getTypeDeclType(ClassDecl)
2227 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2228 }
2229 }
2230
2231 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002232 // Can't check initialization for a base of dependent type or when
2233 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002234 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002235
John McCall31168b02011-06-15 23:02:42 +00002236 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002237
Sebastian Redla74948d2011-09-24 17:48:25 +00002238 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2239 /*IsVirtual=*/false,
2240 Args.getStartLoc(), BaseInit,
2241 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002242 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002243
2244 // C++ [base.class.init]p2:
2245 // If a mem-initializer-id is ambiguous because it designates both
2246 // a direct non-virtual base class and an inherited virtual base
2247 // class, the mem-initializer is ill-formed.
2248 if (DirectBaseSpec && VirtualBaseSpec)
2249 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002250 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002251
2252 CXXBaseSpecifier *BaseSpec
2253 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2254 if (!BaseSpec)
2255 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2256
2257 // Initialize the base.
2258 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00002259 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002260 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002261 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2262 Args.getEndLoc());
2263
2264 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002265 if (BaseInit.isInvalid())
2266 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002267
Sebastian Redla74948d2011-09-24 17:48:25 +00002268 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2269
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002270 // C++0x [class.base.init]p7:
2271 // The initialization of each base and member constitutes a
2272 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002273 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002274 if (BaseInit.isInvalid())
2275 return true;
2276
2277 // If we are in a dependent context, template instantiation will
2278 // perform this type-checking again. Just save the arguments that we
2279 // received in a ParenListExpr.
2280 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2281 // of the information that we have about the base
2282 // initializer. However, deconstructing the ASTs is a dicey process,
2283 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002284 if (CurContext->isDependentContext())
2285 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002286
Alexis Hunt1d792652011-01-08 20:30:50 +00002287 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002288 BaseSpec->isVirtual(),
2289 Args.getStartLoc(),
2290 BaseInit.takeAs<Expr>(),
2291 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002292}
2293
Sebastian Redl22653ba2011-08-30 19:58:05 +00002294// Create a static_cast\<T&&>(expr).
2295static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2296 QualType ExprType = E->getType();
2297 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2298 SourceLocation ExprLoc = E->getLocStart();
2299 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2300 TargetType, ExprLoc);
2301
2302 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2303 SourceRange(ExprLoc, ExprLoc),
2304 E->getSourceRange()).take();
2305}
2306
Anders Carlsson1b00e242010-04-23 03:10:23 +00002307/// ImplicitInitializerKind - How an implicit base or member initializer should
2308/// initialize its base or member.
2309enum ImplicitInitializerKind {
2310 IIK_Default,
2311 IIK_Copy,
2312 IIK_Move
2313};
2314
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002315static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002316BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002317 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002318 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002319 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002320 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002321 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002322 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2323 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002324
John McCalldadc5752010-08-24 06:29:42 +00002325 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002326
2327 switch (ImplicitInitKind) {
2328 case IIK_Default: {
2329 InitializationKind InitKind
2330 = InitializationKind::CreateDefault(Constructor->getLocation());
2331 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2332 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002333 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002334 break;
2335 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002336
Sebastian Redl22653ba2011-08-30 19:58:05 +00002337 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002338 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002339 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002340 ParmVarDecl *Param = Constructor->getParamDecl(0);
2341 QualType ParamType = Param->getType().getNonReferenceType();
2342
2343 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00002344 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002345 Constructor->getLocation(), ParamType,
2346 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002347
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002348 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002349 QualType ArgTy =
2350 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2351 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002352
Sebastian Redl22653ba2011-08-30 19:58:05 +00002353 if (Moving) {
2354 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2355 }
2356
John McCallcf142162010-08-07 06:22:56 +00002357 CXXCastPath BasePath;
2358 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002359 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2360 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002361 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002362 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002363
Anders Carlsson1b00e242010-04-23 03:10:23 +00002364 InitializationKind InitKind
2365 = InitializationKind::CreateDirect(Constructor->getLocation(),
2366 SourceLocation(), SourceLocation());
2367 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2368 &CopyCtorArg, 1);
2369 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002370 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002371 break;
2372 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002373 }
John McCallb268a282010-08-23 23:25:46 +00002374
Douglas Gregora40433a2010-12-07 00:41:46 +00002375 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002376 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002377 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002378
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002379 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002380 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002381 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2382 SourceLocation()),
2383 BaseSpec->isVirtual(),
2384 SourceLocation(),
2385 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002386 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002387 SourceLocation());
2388
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002389 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002390}
2391
Sebastian Redl22653ba2011-08-30 19:58:05 +00002392static bool RefersToRValueRef(Expr *MemRef) {
2393 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2394 return Referenced->getType()->isRValueReferenceType();
2395}
2396
Anders Carlsson3c1db572010-04-23 02:15:47 +00002397static bool
2398BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002399 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002400 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002401 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002402 if (Field->isInvalidDecl())
2403 return true;
2404
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002405 SourceLocation Loc = Constructor->getLocation();
2406
Sebastian Redl22653ba2011-08-30 19:58:05 +00002407 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2408 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002409 ParmVarDecl *Param = Constructor->getParamDecl(0);
2410 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002411
2412 // Suppress copying zero-width bitfields.
2413 if (const Expr *Width = Field->getBitWidth())
2414 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2415 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002416
2417 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00002418 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002419 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002420
Sebastian Redl22653ba2011-08-30 19:58:05 +00002421 if (Moving) {
2422 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2423 }
2424
Douglas Gregor94f9a482010-05-05 05:51:00 +00002425 // Build a reference to this field within the parameter.
2426 CXXScopeSpec SS;
2427 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2428 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002429 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2430 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002431 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002432 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002433 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002434 ParamType, Loc,
2435 /*IsArrow=*/false,
2436 SS,
2437 /*FirstQualifierInScope=*/0,
2438 MemberLookup,
2439 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002440 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002441 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002442
2443 // C++11 [class.copy]p15:
2444 // - if a member m has rvalue reference type T&&, it is direct-initialized
2445 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002446 if (RefersToRValueRef(CtorArg.get())) {
2447 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002448 }
2449
Douglas Gregor94f9a482010-05-05 05:51:00 +00002450 // When the field we are copying is an array, create index variables for
2451 // each dimension of the array. We use these index variables to subscript
2452 // the source array, and other clients (e.g., CodeGen) will perform the
2453 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002454 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002455 QualType BaseType = Field->getType();
2456 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002457 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002458 while (const ConstantArrayType *Array
2459 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002460 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002461 // Create the iteration variable for this array index.
2462 IdentifierInfo *IterationVarName = 0;
2463 {
2464 llvm::SmallString<8> Str;
2465 llvm::raw_svector_ostream OS(Str);
2466 OS << "__i" << IndexVariables.size();
2467 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2468 }
2469 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002470 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002471 IterationVarName, SizeType,
2472 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002473 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002474 IndexVariables.push_back(IterationVar);
2475
2476 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002477 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002478 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002479 assert(!IterationVarRef.isInvalid() &&
2480 "Reference to invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002481
Douglas Gregor94f9a482010-05-05 05:51:00 +00002482 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002483 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002484 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002485 Loc);
2486 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002487 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002488
Douglas Gregor94f9a482010-05-05 05:51:00 +00002489 BaseType = Array->getElementType();
2490 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002491
2492 // The array subscript expression is an lvalue, which is wrong for moving.
2493 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002494 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002495
Douglas Gregor94f9a482010-05-05 05:51:00 +00002496 // Construct the entity that we will be initializing. For an array, this
2497 // will be first element in the array, which may require several levels
2498 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002499 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002500 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002501 if (Indirect)
2502 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2503 else
2504 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002505 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2506 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2507 0,
2508 Entities.back()));
2509
2510 // Direct-initialize to use the copy constructor.
2511 InitializationKind InitKind =
2512 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2513
Sebastian Redle9c4e842011-09-04 18:14:28 +00002514 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002515 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002516 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002517
John McCalldadc5752010-08-24 06:29:42 +00002518 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002519 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002520 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002521 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002522 if (MemberInit.isInvalid())
2523 return true;
2524
Douglas Gregor493627b2011-08-10 15:22:55 +00002525 if (Indirect) {
2526 assert(IndexVariables.size() == 0 &&
2527 "Indirect field improperly initialized");
2528 CXXMemberInit
2529 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2530 Loc, Loc,
2531 MemberInit.takeAs<Expr>(),
2532 Loc);
2533 } else
2534 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2535 Loc, MemberInit.takeAs<Expr>(),
2536 Loc,
2537 IndexVariables.data(),
2538 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002539 return false;
2540 }
2541
Anders Carlsson423f5d82010-04-23 16:04:08 +00002542 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2543
Anders Carlsson3c1db572010-04-23 02:15:47 +00002544 QualType FieldBaseElementType =
2545 SemaRef.Context.getBaseElementType(Field->getType());
2546
Anders Carlsson3c1db572010-04-23 02:15:47 +00002547 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002548 InitializedEntity InitEntity
2549 = Indirect? InitializedEntity::InitializeMember(Indirect)
2550 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002551 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002552 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002553
2554 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002555 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002556 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002557
Douglas Gregora40433a2010-12-07 00:41:46 +00002558 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002559 if (MemberInit.isInvalid())
2560 return true;
2561
Douglas Gregor493627b2011-08-10 15:22:55 +00002562 if (Indirect)
2563 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2564 Indirect, Loc,
2565 Loc,
2566 MemberInit.get(),
2567 Loc);
2568 else
2569 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2570 Field, Loc, Loc,
2571 MemberInit.get(),
2572 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002573 return false;
2574 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002575
Alexis Hunt8b455182011-05-17 00:19:05 +00002576 if (!Field->getParent()->isUnion()) {
2577 if (FieldBaseElementType->isReferenceType()) {
2578 SemaRef.Diag(Constructor->getLocation(),
2579 diag::err_uninitialized_member_in_ctor)
2580 << (int)Constructor->isImplicit()
2581 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2582 << 0 << Field->getDeclName();
2583 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2584 return true;
2585 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002586
Alexis Hunt8b455182011-05-17 00:19:05 +00002587 if (FieldBaseElementType.isConstQualified()) {
2588 SemaRef.Diag(Constructor->getLocation(),
2589 diag::err_uninitialized_member_in_ctor)
2590 << (int)Constructor->isImplicit()
2591 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2592 << 1 << Field->getDeclName();
2593 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2594 return true;
2595 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002596 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002597
John McCall31168b02011-06-15 23:02:42 +00002598 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2599 FieldBaseElementType->isObjCRetainableType() &&
2600 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2601 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2602 // Instant objects:
2603 // Default-initialize Objective-C pointers to NULL.
2604 CXXMemberInit
2605 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2606 Loc, Loc,
2607 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2608 Loc);
2609 return false;
2610 }
2611
Anders Carlsson3c1db572010-04-23 02:15:47 +00002612 // Nothing to initialize.
2613 CXXMemberInit = 0;
2614 return false;
2615}
John McCallbc83b3f2010-05-20 23:23:51 +00002616
2617namespace {
2618struct BaseAndFieldInfo {
2619 Sema &S;
2620 CXXConstructorDecl *Ctor;
2621 bool AnyErrorsInInits;
2622 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002623 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002624 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002625
2626 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2627 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002628 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2629 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002630 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002631 else if (Generated && Ctor->isMoveConstructor())
2632 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002633 else
2634 IIK = IIK_Default;
2635 }
2636};
2637}
2638
Richard Smithc94ec842011-09-19 13:34:43 +00002639/// \brief Determine whether the given indirect field declaration is somewhere
2640/// within an anonymous union.
2641static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2642 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2643 CEnd = F->chain_end();
2644 C != CEnd; ++C)
2645 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2646 if (Record->isUnion())
2647 return true;
2648
2649 return false;
2650}
2651
Richard Smith938f40b2011-06-11 17:19:42 +00002652static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002653 FieldDecl *Field,
2654 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002655
Chandler Carruth139e9622010-06-30 02:59:29 +00002656 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002657 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002658 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002659 return false;
2660 }
2661
Richard Smith938f40b2011-06-11 17:19:42 +00002662 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2663 // has a brace-or-equal-initializer, the entity is initialized as specified
2664 // in [dcl.init].
2665 if (Field->hasInClassInitializer()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002666 CXXCtorInitializer *Init;
2667 if (Indirect)
2668 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2669 SourceLocation(),
2670 SourceLocation(), 0,
2671 SourceLocation());
2672 else
2673 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2674 SourceLocation(),
2675 SourceLocation(), 0,
2676 SourceLocation());
2677 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002678 return false;
2679 }
2680
Richard Smith12d5ed82011-09-18 11:14:50 +00002681 // Don't build an implicit initializer for union members if none was
2682 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002683 if (Field->getParent()->isUnion() ||
2684 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002685 return false;
2686
John McCallbc83b3f2010-05-20 23:23:51 +00002687 // Don't try to build an implicit initializer if there were semantic
2688 // errors in any of the initializers (and therefore we might be
2689 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002690 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002691 return false;
2692
Alexis Hunt1d792652011-01-08 20:30:50 +00002693 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002694 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2695 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002696 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002697
Francois Pichetd583da02010-12-04 09:14:42 +00002698 if (Init)
2699 Info.AllToInit.push_back(Init);
2700
John McCallbc83b3f2010-05-20 23:23:51 +00002701 return false;
2702}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002703
2704bool
2705Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2706 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002707 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002708 Constructor->setNumCtorInitializers(1);
2709 CXXCtorInitializer **initializer =
2710 new (Context) CXXCtorInitializer*[1];
2711 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2712 Constructor->setCtorInitializers(initializer);
2713
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002714 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2715 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2716 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2717 }
2718
Alexis Hunte2622992011-05-05 00:05:47 +00002719 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002720
Alexis Hunt61bc1732011-05-01 07:04:31 +00002721 return false;
2722}
Douglas Gregor493627b2011-08-10 15:22:55 +00002723
John McCall1b1a1db2011-06-17 00:18:42 +00002724bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2725 CXXCtorInitializer **Initializers,
2726 unsigned NumInitializers,
2727 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002728 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002729 // Just store the initializers as written, they will be checked during
2730 // instantiation.
2731 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002732 Constructor->setNumCtorInitializers(NumInitializers);
2733 CXXCtorInitializer **baseOrMemberInitializers =
2734 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002735 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002736 NumInitializers * sizeof(CXXCtorInitializer*));
2737 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002738 }
2739
2740 return false;
2741 }
2742
John McCallbc83b3f2010-05-20 23:23:51 +00002743 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002744
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002745 // We need to build the initializer AST according to order of construction
2746 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002747 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002748 if (!ClassDecl)
2749 return true;
2750
Eli Friedman9cf6b592009-11-09 19:20:36 +00002751 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002752
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002753 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002754 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002755
2756 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002757 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002758 else
Francois Pichetd583da02010-12-04 09:14:42 +00002759 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002760 }
2761
Anders Carlsson43c64af2010-04-21 19:52:01 +00002762 // Keep track of the direct virtual bases.
2763 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2764 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2765 E = ClassDecl->bases_end(); I != E; ++I) {
2766 if (I->isVirtual())
2767 DirectVBases.insert(I);
2768 }
2769
Anders Carlssondb0a9652010-04-02 06:26:44 +00002770 // Push virtual bases before others.
2771 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2772 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2773
Alexis Hunt1d792652011-01-08 20:30:50 +00002774 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002775 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2776 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002777 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002778 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002779 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002780 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002781 VBase, IsInheritedVirtualBase,
2782 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002783 HadError = true;
2784 continue;
2785 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002786
John McCallbc83b3f2010-05-20 23:23:51 +00002787 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002788 }
2789 }
Mike Stump11289f42009-09-09 15:08:12 +00002790
John McCallbc83b3f2010-05-20 23:23:51 +00002791 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2793 E = ClassDecl->bases_end(); Base != E; ++Base) {
2794 // Virtuals are in the virtual base list and already constructed.
2795 if (Base->isVirtual())
2796 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002797
Alexis Hunt1d792652011-01-08 20:30:50 +00002798 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002799 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2800 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002801 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002802 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002803 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002804 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002805 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002806 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002807 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002808 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002809
John McCallbc83b3f2010-05-20 23:23:51 +00002810 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002811 }
2812 }
Mike Stump11289f42009-09-09 15:08:12 +00002813
John McCallbc83b3f2010-05-20 23:23:51 +00002814 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002815 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2816 MemEnd = ClassDecl->decls_end();
2817 Mem != MemEnd; ++Mem) {
2818 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2819 if (F->getType()->isIncompleteArrayType()) {
2820 assert(ClassDecl->hasFlexibleArrayMember() &&
2821 "Incomplete array type is not valid");
2822 continue;
2823 }
2824
Sebastian Redl22653ba2011-08-30 19:58:05 +00002825 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002826 // handle anonymous struct/union fields based on their individual
2827 // indirect fields.
2828 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2829 continue;
2830
2831 if (CollectFieldInitializer(*this, Info, F))
2832 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002833 continue;
2834 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002835
2836 // Beyond this point, we only consider default initialization.
2837 if (Info.IIK != IIK_Default)
2838 continue;
2839
2840 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2841 if (F->getType()->isIncompleteArrayType()) {
2842 assert(ClassDecl->hasFlexibleArrayMember() &&
2843 "Incomplete array type is not valid");
2844 continue;
2845 }
2846
Douglas Gregor493627b2011-08-10 15:22:55 +00002847 // Initialize each field of an anonymous struct individually.
2848 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2849 HadError = true;
2850
2851 continue;
2852 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002853 }
Mike Stump11289f42009-09-09 15:08:12 +00002854
John McCallbc83b3f2010-05-20 23:23:51 +00002855 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002856 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002857 Constructor->setNumCtorInitializers(NumInitializers);
2858 CXXCtorInitializer **baseOrMemberInitializers =
2859 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002860 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002861 NumInitializers * sizeof(CXXCtorInitializer*));
2862 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002863
John McCalla6309952010-03-16 21:39:52 +00002864 // Constructors implicitly reference the base and member
2865 // destructors.
2866 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2867 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002868 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002869
2870 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002871}
2872
Eli Friedman952c15d2009-07-21 19:28:10 +00002873static void *GetKeyForTopLevelField(FieldDecl *Field) {
2874 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002875 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002876 if (RT->getDecl()->isAnonymousStructOrUnion())
2877 return static_cast<void *>(RT->getDecl());
2878 }
2879 return static_cast<void *>(Field);
2880}
2881
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002882static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002883 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002884}
2885
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002886static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002887 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002888 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002889 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002890
Eli Friedman952c15d2009-07-21 19:28:10 +00002891 // For fields injected into the class via declaration of an anonymous union,
2892 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002893 FieldDecl *Field = Member->getAnyMember();
2894
John McCall23eebd92010-04-10 09:28:51 +00002895 // If the field is a member of an anonymous struct or union, our key
2896 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002897 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002898 if (RD->isAnonymousStructOrUnion()) {
2899 while (true) {
2900 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2901 if (Parent->isAnonymousStructOrUnion())
2902 RD = Parent;
2903 else
2904 break;
2905 }
2906
Anders Carlsson83ac3122010-03-30 16:19:37 +00002907 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002908 }
Mike Stump11289f42009-09-09 15:08:12 +00002909
Anders Carlssona942dcd2010-03-30 15:39:27 +00002910 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002911}
2912
Anders Carlssone857b292010-04-02 03:37:03 +00002913static void
2914DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002915 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002916 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002917 unsigned NumInits) {
2918 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002919 return;
Mike Stump11289f42009-09-09 15:08:12 +00002920
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002921 // Don't check initializers order unless the warning is enabled at the
2922 // location of at least one initializer.
2923 bool ShouldCheckOrder = false;
2924 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002925 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002926 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2927 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00002928 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002929 ShouldCheckOrder = true;
2930 break;
2931 }
2932 }
2933 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002934 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002935
John McCallbb7b6582010-04-10 07:37:23 +00002936 // Build the list of bases and members in the order that they'll
2937 // actually be initialized. The explicit initializers should be in
2938 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002939 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002940
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002941 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2942
John McCallbb7b6582010-04-10 07:37:23 +00002943 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002944 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002945 ClassDecl->vbases_begin(),
2946 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002947 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002948
John McCallbb7b6582010-04-10 07:37:23 +00002949 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002950 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002951 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002952 if (Base->isVirtual())
2953 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002954 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002955 }
Mike Stump11289f42009-09-09 15:08:12 +00002956
John McCallbb7b6582010-04-10 07:37:23 +00002957 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002958 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2959 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002960 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002961
John McCallbb7b6582010-04-10 07:37:23 +00002962 unsigned NumIdealInits = IdealInitKeys.size();
2963 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002964
Alexis Hunt1d792652011-01-08 20:30:50 +00002965 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002966 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002967 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002968 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002969
2970 // Scan forward to try to find this initializer in the idealized
2971 // initializers list.
2972 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2973 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002974 break;
John McCallbb7b6582010-04-10 07:37:23 +00002975
2976 // If we didn't find this initializer, it must be because we
2977 // scanned past it on a previous iteration. That can only
2978 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002979 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002980 Sema::SemaDiagnosticBuilder D =
2981 SemaRef.Diag(PrevInit->getSourceLocation(),
2982 diag::warn_initializer_out_of_order);
2983
Francois Pichetd583da02010-12-04 09:14:42 +00002984 if (PrevInit->isAnyMemberInitializer())
2985 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002986 else
2987 D << 1 << PrevInit->getBaseClassInfo()->getType();
2988
Francois Pichetd583da02010-12-04 09:14:42 +00002989 if (Init->isAnyMemberInitializer())
2990 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002991 else
2992 D << 1 << Init->getBaseClassInfo()->getType();
2993
2994 // Move back to the initializer's location in the ideal list.
2995 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2996 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002997 break;
John McCallbb7b6582010-04-10 07:37:23 +00002998
2999 assert(IdealIndex != NumIdealInits &&
3000 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003001 }
John McCallbb7b6582010-04-10 07:37:23 +00003002
3003 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003004 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003005}
3006
John McCall23eebd92010-04-10 09:28:51 +00003007namespace {
3008bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003009 CXXCtorInitializer *Init,
3010 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003011 if (!PrevInit) {
3012 PrevInit = Init;
3013 return false;
3014 }
3015
3016 if (FieldDecl *Field = Init->getMember())
3017 S.Diag(Init->getSourceLocation(),
3018 diag::err_multiple_mem_initialization)
3019 << Field->getDeclName()
3020 << Init->getSourceRange();
3021 else {
John McCall424cec92011-01-19 06:33:43 +00003022 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003023 assert(BaseClass && "neither field nor base");
3024 S.Diag(Init->getSourceLocation(),
3025 diag::err_multiple_base_initialization)
3026 << QualType(BaseClass, 0)
3027 << Init->getSourceRange();
3028 }
3029 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3030 << 0 << PrevInit->getSourceRange();
3031
3032 return true;
3033}
3034
Alexis Hunt1d792652011-01-08 20:30:50 +00003035typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003036typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3037
3038bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003039 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003040 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003041 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003042 RecordDecl *Parent = Field->getParent();
3043 if (!Parent->isAnonymousStructOrUnion())
3044 return false;
3045
3046 NamedDecl *Child = Field;
3047 do {
3048 if (Parent->isUnion()) {
3049 UnionEntry &En = Unions[Parent];
3050 if (En.first && En.first != Child) {
3051 S.Diag(Init->getSourceLocation(),
3052 diag::err_multiple_mem_union_initialization)
3053 << Field->getDeclName()
3054 << Init->getSourceRange();
3055 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3056 << 0 << En.second->getSourceRange();
3057 return true;
3058 } else if (!En.first) {
3059 En.first = Child;
3060 En.second = Init;
3061 }
3062 }
3063
3064 Child = Parent;
3065 Parent = cast<RecordDecl>(Parent->getDeclContext());
3066 } while (Parent->isAnonymousStructOrUnion());
3067
3068 return false;
3069}
3070}
3071
Anders Carlssone857b292010-04-02 03:37:03 +00003072/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003073void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003074 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00003075 CXXCtorInitializer **meminits,
3076 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003077 bool AnyErrors) {
3078 if (!ConstructorDecl)
3079 return;
3080
3081 AdjustDeclIfTemplate(ConstructorDecl);
3082
3083 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003084 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003085
3086 if (!Constructor) {
3087 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3088 return;
3089 }
3090
Alexis Hunt1d792652011-01-08 20:30:50 +00003091 CXXCtorInitializer **MemInits =
3092 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00003093
3094 // Mapping for the duplicate initializers check.
3095 // For member initializers, this is keyed with a FieldDecl*.
3096 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003097 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003098
3099 // Mapping for the inconsistent anonymous-union initializers check.
3100 RedundantUnionMap MemberUnions;
3101
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003102 bool HadError = false;
3103 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003104 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003105
Abramo Bagnara341d7832010-05-26 18:09:23 +00003106 // Set the source order index.
3107 Init->setSourceOrder(i);
3108
Francois Pichetd583da02010-12-04 09:14:42 +00003109 if (Init->isAnyMemberInitializer()) {
3110 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003111 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3112 CheckRedundantUnionInit(*this, Init, MemberUnions))
3113 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003114 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003115 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3116 if (CheckRedundantInit(*this, Init, Members[Key]))
3117 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003118 } else {
3119 assert(Init->isDelegatingInitializer());
3120 // This must be the only initializer
3121 if (i != 0 || NumMemInits > 1) {
3122 Diag(MemInits[0]->getSourceLocation(),
3123 diag::err_delegating_initializer_alone)
3124 << MemInits[0]->getSourceRange();
3125 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00003126 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003127 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003128 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003129 // Return immediately as the initializer is set.
3130 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003131 }
Anders Carlssone857b292010-04-02 03:37:03 +00003132 }
3133
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003134 if (HadError)
3135 return;
3136
Anders Carlssone857b292010-04-02 03:37:03 +00003137 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003138
Alexis Hunt1d792652011-01-08 20:30:50 +00003139 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00003140}
3141
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003142void
John McCalla6309952010-03-16 21:39:52 +00003143Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3144 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003145 // Ignore dependent contexts. Also ignore unions, since their members never
3146 // have destructors implicitly called.
3147 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003148 return;
John McCall1064d7e2010-03-16 05:22:47 +00003149
3150 // FIXME: all the access-control diagnostics are positioned on the
3151 // field/base declaration. That's probably good; that said, the
3152 // user might reasonably want to know why the destructor is being
3153 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003154
Anders Carlssondee9a302009-11-17 04:44:12 +00003155 // Non-static data members.
3156 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3157 E = ClassDecl->field_end(); I != E; ++I) {
3158 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003159 if (Field->isInvalidDecl())
3160 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003161 QualType FieldType = Context.getBaseElementType(Field->getType());
3162
3163 const RecordType* RT = FieldType->getAs<RecordType>();
3164 if (!RT)
3165 continue;
3166
3167 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003168 if (FieldClassDecl->isInvalidDecl())
3169 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003170 if (FieldClassDecl->hasTrivialDestructor())
3171 continue;
3172
Douglas Gregore71edda2010-07-01 22:47:18 +00003173 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003174 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003175 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003176 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003177 << Field->getDeclName()
3178 << FieldType);
3179
John McCalla6309952010-03-16 21:39:52 +00003180 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003181 }
3182
John McCall1064d7e2010-03-16 05:22:47 +00003183 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3184
Anders Carlssondee9a302009-11-17 04:44:12 +00003185 // Bases.
3186 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3187 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003188 // Bases are always records in a well-formed non-dependent class.
3189 const RecordType *RT = Base->getType()->getAs<RecordType>();
3190
3191 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003192 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003193 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003194
John McCall1064d7e2010-03-16 05:22:47 +00003195 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003196 // If our base class is invalid, we probably can't get its dtor anyway.
3197 if (BaseClassDecl->isInvalidDecl())
3198 continue;
3199 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00003200 if (BaseClassDecl->hasTrivialDestructor())
3201 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003202
Douglas Gregore71edda2010-07-01 22:47:18 +00003203 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003204 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003205
3206 // FIXME: caret should be on the start of the class name
3207 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003208 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003209 << Base->getType()
3210 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00003211
John McCalla6309952010-03-16 21:39:52 +00003212 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003213 }
3214
3215 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003216 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3217 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003218
3219 // Bases are always records in a well-formed non-dependent class.
3220 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3221
3222 // Ignore direct virtual bases.
3223 if (DirectVirtualBases.count(RT))
3224 continue;
3225
John McCall1064d7e2010-03-16 05:22:47 +00003226 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003227 // If our base class is invalid, we probably can't get its dtor anyway.
3228 if (BaseClassDecl->isInvalidDecl())
3229 continue;
3230 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003231 if (BaseClassDecl->hasTrivialDestructor())
3232 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003233
Douglas Gregore71edda2010-07-01 22:47:18 +00003234 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003235 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003236 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003237 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00003238 << VBase->getType());
3239
John McCalla6309952010-03-16 21:39:52 +00003240 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003241 }
3242}
3243
John McCall48871652010-08-21 09:40:31 +00003244void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003245 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003246 return;
Mike Stump11289f42009-09-09 15:08:12 +00003247
Mike Stump11289f42009-09-09 15:08:12 +00003248 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003249 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00003250 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003251}
3252
Mike Stump11289f42009-09-09 15:08:12 +00003253bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003254 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00003255 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00003256 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00003257 else
John McCall02db245d2010-08-18 09:41:07 +00003258 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00003259}
3260
Anders Carlssoneabf7702009-08-27 00:13:57 +00003261bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003262 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003263 if (!getLangOptions().CPlusPlus)
3264 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003265
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003266 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00003267 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00003268
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003269 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003270 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003271 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003272 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003273
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003274 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00003275 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003276 }
Mike Stump11289f42009-09-09 15:08:12 +00003277
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003278 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003279 if (!RT)
3280 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003281
John McCall67da35c2010-02-04 22:26:26 +00003282 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003283
John McCall02db245d2010-08-18 09:41:07 +00003284 // We can't answer whether something is abstract until it has a
3285 // definition. If it's currently being defined, we'll walk back
3286 // over all the declarations when we have a full definition.
3287 const CXXRecordDecl *Def = RD->getDefinition();
3288 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003289 return false;
3290
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003291 if (!RD->isAbstract())
3292 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003293
Anders Carlssoneabf7702009-08-27 00:13:57 +00003294 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00003295 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003296
John McCall02db245d2010-08-18 09:41:07 +00003297 return true;
3298}
3299
3300void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3301 // Check if we've already emitted the list of pure virtual functions
3302 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003303 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003304 return;
Mike Stump11289f42009-09-09 15:08:12 +00003305
Douglas Gregor4165bd62010-03-23 23:47:56 +00003306 CXXFinalOverriderMap FinalOverriders;
3307 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003308
Anders Carlssona2f74f32010-06-03 01:00:02 +00003309 // Keep a set of seen pure methods so we won't diagnose the same method
3310 // more than once.
3311 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3312
Douglas Gregor4165bd62010-03-23 23:47:56 +00003313 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3314 MEnd = FinalOverriders.end();
3315 M != MEnd;
3316 ++M) {
3317 for (OverridingMethods::iterator SO = M->second.begin(),
3318 SOEnd = M->second.end();
3319 SO != SOEnd; ++SO) {
3320 // C++ [class.abstract]p4:
3321 // A class is abstract if it contains or inherits at least one
3322 // pure virtual function for which the final overrider is pure
3323 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003324
Douglas Gregor4165bd62010-03-23 23:47:56 +00003325 //
3326 if (SO->second.size() != 1)
3327 continue;
3328
3329 if (!SO->second.front().Method->isPure())
3330 continue;
3331
Anders Carlssona2f74f32010-06-03 01:00:02 +00003332 if (!SeenPureMethods.insert(SO->second.front().Method))
3333 continue;
3334
Douglas Gregor4165bd62010-03-23 23:47:56 +00003335 Diag(SO->second.front().Method->getLocation(),
3336 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003337 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003338 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003339 }
3340
3341 if (!PureVirtualClassDiagSet)
3342 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3343 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003344}
3345
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003346namespace {
John McCall02db245d2010-08-18 09:41:07 +00003347struct AbstractUsageInfo {
3348 Sema &S;
3349 CXXRecordDecl *Record;
3350 CanQualType AbstractType;
3351 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003352
John McCall02db245d2010-08-18 09:41:07 +00003353 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3354 : S(S), Record(Record),
3355 AbstractType(S.Context.getCanonicalType(
3356 S.Context.getTypeDeclType(Record))),
3357 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003358
John McCall02db245d2010-08-18 09:41:07 +00003359 void DiagnoseAbstractType() {
3360 if (Invalid) return;
3361 S.DiagnoseAbstractType(Record);
3362 Invalid = true;
3363 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003364
John McCall02db245d2010-08-18 09:41:07 +00003365 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3366};
3367
3368struct CheckAbstractUsage {
3369 AbstractUsageInfo &Info;
3370 const NamedDecl *Ctx;
3371
3372 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3373 : Info(Info), Ctx(Ctx) {}
3374
3375 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3376 switch (TL.getTypeLocClass()) {
3377#define ABSTRACT_TYPELOC(CLASS, PARENT)
3378#define TYPELOC(CLASS, PARENT) \
3379 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3380#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003381 }
John McCall02db245d2010-08-18 09:41:07 +00003382 }
Mike Stump11289f42009-09-09 15:08:12 +00003383
John McCall02db245d2010-08-18 09:41:07 +00003384 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3385 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3386 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003387 if (!TL.getArg(I))
3388 continue;
3389
John McCall02db245d2010-08-18 09:41:07 +00003390 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3391 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003392 }
John McCall02db245d2010-08-18 09:41:07 +00003393 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003394
John McCall02db245d2010-08-18 09:41:07 +00003395 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3396 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3397 }
Mike Stump11289f42009-09-09 15:08:12 +00003398
John McCall02db245d2010-08-18 09:41:07 +00003399 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3400 // Visit the type parameters from a permissive context.
3401 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3402 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3403 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3404 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3405 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3406 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003407 }
John McCall02db245d2010-08-18 09:41:07 +00003408 }
Mike Stump11289f42009-09-09 15:08:12 +00003409
John McCall02db245d2010-08-18 09:41:07 +00003410 // Visit pointee types from a permissive context.
3411#define CheckPolymorphic(Type) \
3412 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3413 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3414 }
3415 CheckPolymorphic(PointerTypeLoc)
3416 CheckPolymorphic(ReferenceTypeLoc)
3417 CheckPolymorphic(MemberPointerTypeLoc)
3418 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00003419 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003420
John McCall02db245d2010-08-18 09:41:07 +00003421 /// Handle all the types we haven't given a more specific
3422 /// implementation for above.
3423 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3424 // Every other kind of type that we haven't called out already
3425 // that has an inner type is either (1) sugar or (2) contains that
3426 // inner type in some way as a subobject.
3427 if (TypeLoc Next = TL.getNextTypeLoc())
3428 return Visit(Next, Sel);
3429
3430 // If there's no inner type and we're in a permissive context,
3431 // don't diagnose.
3432 if (Sel == Sema::AbstractNone) return;
3433
3434 // Check whether the type matches the abstract type.
3435 QualType T = TL.getType();
3436 if (T->isArrayType()) {
3437 Sel = Sema::AbstractArrayType;
3438 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003439 }
John McCall02db245d2010-08-18 09:41:07 +00003440 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3441 if (CT != Info.AbstractType) return;
3442
3443 // It matched; do some magic.
3444 if (Sel == Sema::AbstractArrayType) {
3445 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3446 << T << TL.getSourceRange();
3447 } else {
3448 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3449 << Sel << T << TL.getSourceRange();
3450 }
3451 Info.DiagnoseAbstractType();
3452 }
3453};
3454
3455void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3456 Sema::AbstractDiagSelID Sel) {
3457 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3458}
3459
3460}
3461
3462/// Check for invalid uses of an abstract type in a method declaration.
3463static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3464 CXXMethodDecl *MD) {
3465 // No need to do the check on definitions, which require that
3466 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003467 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003468 return;
3469
3470 // For safety's sake, just ignore it if we don't have type source
3471 // information. This should never happen for non-implicit methods,
3472 // but...
3473 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3474 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3475}
3476
3477/// Check for invalid uses of an abstract type within a class definition.
3478static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3479 CXXRecordDecl *RD) {
3480 for (CXXRecordDecl::decl_iterator
3481 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3482 Decl *D = *I;
3483 if (D->isImplicit()) continue;
3484
3485 // Methods and method templates.
3486 if (isa<CXXMethodDecl>(D)) {
3487 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3488 } else if (isa<FunctionTemplateDecl>(D)) {
3489 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3490 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3491
3492 // Fields and static variables.
3493 } else if (isa<FieldDecl>(D)) {
3494 FieldDecl *FD = cast<FieldDecl>(D);
3495 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3496 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3497 } else if (isa<VarDecl>(D)) {
3498 VarDecl *VD = cast<VarDecl>(D);
3499 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3500 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3501
3502 // Nested classes and class templates.
3503 } else if (isa<CXXRecordDecl>(D)) {
3504 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3505 } else if (isa<ClassTemplateDecl>(D)) {
3506 CheckAbstractClassUsage(Info,
3507 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3508 }
3509 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003510}
3511
Douglas Gregorc99f1552009-12-03 18:33:45 +00003512/// \brief Perform semantic checks on a class definition that has been
3513/// completing, introducing implicitly-declared members, checking for
3514/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003515void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003516 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003517 return;
3518
John McCall02db245d2010-08-18 09:41:07 +00003519 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3520 AbstractUsageInfo Info(*this, Record);
3521 CheckAbstractClassUsage(Info, Record);
3522 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003523
3524 // If this is not an aggregate type and has no user-declared constructor,
3525 // complain about any non-static data members of reference or const scalar
3526 // type, since they will never get initializers.
3527 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3528 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3529 bool Complained = false;
3530 for (RecordDecl::field_iterator F = Record->field_begin(),
3531 FEnd = Record->field_end();
3532 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003533 if (F->hasInClassInitializer())
3534 continue;
3535
Douglas Gregor454a5b62010-04-15 00:00:53 +00003536 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003537 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003538 if (!Complained) {
3539 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3540 << Record->getTagKind() << Record;
3541 Complained = true;
3542 }
3543
3544 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3545 << F->getType()->isReferenceType()
3546 << F->getDeclName();
3547 }
3548 }
3549 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003550
Anders Carlssone771e762011-01-25 18:08:22 +00003551 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003552 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003553
3554 if (Record->getIdentifier()) {
3555 // C++ [class.mem]p13:
3556 // If T is the name of a class, then each of the following shall have a
3557 // name different from T:
3558 // - every member of every anonymous union that is a member of class T.
3559 //
3560 // C++ [class.mem]p14:
3561 // In addition, if class T has a user-declared constructor (12.1), every
3562 // non-static data member of class T shall have a name different from T.
3563 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003564 R.first != R.second; ++R.first) {
3565 NamedDecl *D = *R.first;
3566 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3567 isa<IndirectFieldDecl>(D)) {
3568 Diag(D->getLocation(), diag::err_member_name_of_class)
3569 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003570 break;
3571 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003572 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003573 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003574
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003575 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003576 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003577 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003578 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003579 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3580 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3581 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003582
3583 // See if a method overloads virtual methods in a base
3584 /// class without overriding any.
3585 if (!Record->isDependentType()) {
3586 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3587 MEnd = Record->method_end();
3588 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003589 if (!(*M)->isStatic())
3590 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003591 }
3592 }
Sebastian Redl08905022011-02-05 19:23:19 +00003593
Richard Smitheb3c10c2011-10-01 02:31:28 +00003594 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3595 // function that is not a constructor declares that member function to be
3596 // const. [...] The class of which that function is a member shall be
3597 // a literal type.
3598 //
3599 // It's fine to diagnose constructors here too: such constructors cannot
3600 // produce a constant expression, so are ill-formed (no diagnostic required).
3601 //
3602 // If the class has virtual bases, any constexpr members will already have
3603 // been diagnosed by the checks performed on the member declaration, so
3604 // suppress this (less useful) diagnostic.
3605 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3606 !Record->isLiteral() && !Record->getNumVBases()) {
3607 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3608 MEnd = Record->method_end();
3609 M != MEnd; ++M) {
3610 if ((*M)->isConstexpr()) {
3611 switch (Record->getTemplateSpecializationKind()) {
3612 case TSK_ImplicitInstantiation:
3613 case TSK_ExplicitInstantiationDeclaration:
3614 case TSK_ExplicitInstantiationDefinition:
3615 // If a template instantiates to a non-literal type, but its members
3616 // instantiate to constexpr functions, the template is technically
3617 // ill-formed, but we allow it for sanity. Such members are treated as
3618 // non-constexpr.
3619 (*M)->setConstexpr(false);
3620 continue;
3621
3622 case TSK_Undeclared:
3623 case TSK_ExplicitSpecialization:
3624 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3625 PDiag(diag::err_constexpr_method_non_literal));
3626 break;
3627 }
3628
3629 // Only produce one error per class.
3630 break;
3631 }
3632 }
3633 }
3634
Sebastian Redl08905022011-02-05 19:23:19 +00003635 // Declare inherited constructors. We do this eagerly here because:
3636 // - The standard requires an eager diagnostic for conflicting inherited
3637 // constructors from different classes.
3638 // - The lazy declaration of the other implicit constructors is so as to not
3639 // waste space and performance on classes that are not meant to be
3640 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3641 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003642 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003643
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003644 if (!Record->isDependentType())
3645 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003646}
3647
3648void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003649 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3650 ME = Record->method_end();
3651 MI != ME; ++MI) {
3652 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3653 switch (getSpecialMember(*MI)) {
3654 case CXXDefaultConstructor:
3655 CheckExplicitlyDefaultedDefaultConstructor(
3656 cast<CXXConstructorDecl>(*MI));
3657 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003658
Alexis Huntf91729462011-05-12 22:46:25 +00003659 case CXXDestructor:
3660 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3661 break;
3662
3663 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003664 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3665 break;
3666
Alexis Huntf91729462011-05-12 22:46:25 +00003667 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003668 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003669 break;
3670
Alexis Hunt119c10e2011-05-25 23:16:36 +00003671 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003672 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003673 break;
3674
Sebastian Redl22653ba2011-08-30 19:58:05 +00003675 case CXXMoveAssignment:
3676 CheckExplicitlyDefaultedMoveAssignment(*MI);
3677 break;
3678
3679 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003680 llvm_unreachable("non-special member explicitly defaulted!");
3681 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003682 }
3683 }
3684
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003685}
3686
3687void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3688 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3689
3690 // Whether this was the first-declared instance of the constructor.
3691 // This affects whether we implicitly add an exception spec (and, eventually,
3692 // constexpr). It is also ill-formed to explicitly default a constructor such
3693 // that it would be deleted. (C++0x [decl.fct.def.default])
3694 bool First = CD == CD->getCanonicalDecl();
3695
Alexis Hunt913820d2011-05-13 06:10:58 +00003696 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003697 if (CD->getNumParams() != 0) {
3698 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3699 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003700 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003701 }
3702
3703 ImplicitExceptionSpecification Spec
3704 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3705 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003706 if (EPI.ExceptionSpecType == EST_Delayed) {
3707 // Exception specification depends on some deferred part of the class. We'll
3708 // try again when the class's definition has been fully processed.
3709 return;
3710 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003711 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3712 *ExceptionType = Context.getFunctionType(
3713 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3714
3715 if (CtorType->hasExceptionSpec()) {
3716 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003717 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003718 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003719 PDiag(),
3720 ExceptionType, SourceLocation(),
3721 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003722 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003723 }
3724 } else if (First) {
3725 // We set the declaration to have the computed exception spec here.
3726 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003727 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003728 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3729 }
Alexis Huntb3153022011-05-12 03:51:48 +00003730
Alexis Hunt913820d2011-05-13 06:10:58 +00003731 if (HadError) {
3732 CD->setInvalidDecl();
3733 return;
3734 }
3735
Alexis Huntd6da8762011-10-10 06:18:57 +00003736 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003737 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003738 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003739 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003740 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003741 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003742 CD->setInvalidDecl();
3743 }
3744 }
3745}
3746
3747void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3748 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3749
3750 // Whether this was the first-declared instance of the constructor.
3751 bool First = CD == CD->getCanonicalDecl();
3752
3753 bool HadError = false;
3754 if (CD->getNumParams() != 1) {
3755 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3756 << CD->getSourceRange();
3757 HadError = true;
3758 }
3759
3760 ImplicitExceptionSpecification Spec(Context);
3761 bool Const;
3762 llvm::tie(Spec, Const) =
3763 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3764
3765 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3766 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3767 *ExceptionType = Context.getFunctionType(
3768 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3769
3770 // Check for parameter type matching.
3771 // This is a copy ctor so we know it's a cv-qualified reference to T.
3772 QualType ArgType = CtorType->getArgType(0);
3773 if (ArgType->getPointeeType().isVolatileQualified()) {
3774 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3775 HadError = true;
3776 }
3777 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3778 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3779 HadError = true;
3780 }
3781
3782 if (CtorType->hasExceptionSpec()) {
3783 if (CheckEquivalentExceptionSpec(
3784 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003785 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003786 PDiag(),
3787 ExceptionType, SourceLocation(),
3788 CtorType, CD->getLocation())) {
3789 HadError = true;
3790 }
3791 } else if (First) {
3792 // We set the declaration to have the computed exception spec here.
3793 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003794 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003795 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3796 }
3797
3798 if (HadError) {
3799 CD->setInvalidDecl();
3800 return;
3801 }
3802
3803 if (ShouldDeleteCopyConstructor(CD)) {
3804 if (First) {
3805 CD->setDeletedAsWritten();
3806 } else {
3807 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003808 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003809 CD->setInvalidDecl();
3810 }
Alexis Huntb3153022011-05-12 03:51:48 +00003811 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003812}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003813
Alexis Huntc9a55732011-05-14 05:23:28 +00003814void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3815 assert(MD->isExplicitlyDefaulted());
3816
3817 // Whether this was the first-declared instance of the operator
3818 bool First = MD == MD->getCanonicalDecl();
3819
3820 bool HadError = false;
3821 if (MD->getNumParams() != 1) {
3822 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3823 << MD->getSourceRange();
3824 HadError = true;
3825 }
3826
3827 QualType ReturnType =
3828 MD->getType()->getAs<FunctionType>()->getResultType();
3829 if (!ReturnType->isLValueReferenceType() ||
3830 !Context.hasSameType(
3831 Context.getCanonicalType(ReturnType->getPointeeType()),
3832 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3833 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3834 HadError = true;
3835 }
3836
3837 ImplicitExceptionSpecification Spec(Context);
3838 bool Const;
3839 llvm::tie(Spec, Const) =
3840 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3841
3842 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3843 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3844 *ExceptionType = Context.getFunctionType(
3845 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3846
Alexis Huntc9a55732011-05-14 05:23:28 +00003847 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003848 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00003849 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003850 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003851 } else {
3852 if (ArgType->getPointeeType().isVolatileQualified()) {
3853 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3854 HadError = true;
3855 }
3856 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3857 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3858 HadError = true;
3859 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003860 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003861
Alexis Huntc9a55732011-05-14 05:23:28 +00003862 if (OperType->getTypeQuals()) {
3863 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3864 HadError = true;
3865 }
3866
3867 if (OperType->hasExceptionSpec()) {
3868 if (CheckEquivalentExceptionSpec(
3869 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003870 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003871 PDiag(),
3872 ExceptionType, SourceLocation(),
3873 OperType, MD->getLocation())) {
3874 HadError = true;
3875 }
3876 } else if (First) {
3877 // We set the declaration to have the computed exception spec here.
3878 // We duplicate the one parameter type.
3879 EPI.RefQualifier = OperType->getRefQualifier();
3880 EPI.ExtInfo = OperType->getExtInfo();
3881 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3882 }
3883
3884 if (HadError) {
3885 MD->setInvalidDecl();
3886 return;
3887 }
3888
3889 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3890 if (First) {
3891 MD->setDeletedAsWritten();
3892 } else {
3893 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003894 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003895 MD->setInvalidDecl();
3896 }
3897 }
3898}
3899
Sebastian Redl22653ba2011-08-30 19:58:05 +00003900void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3901 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3902
3903 // Whether this was the first-declared instance of the constructor.
3904 bool First = CD == CD->getCanonicalDecl();
3905
3906 bool HadError = false;
3907 if (CD->getNumParams() != 1) {
3908 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3909 << CD->getSourceRange();
3910 HadError = true;
3911 }
3912
3913 ImplicitExceptionSpecification Spec(
3914 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3915
3916 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3917 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3918 *ExceptionType = Context.getFunctionType(
3919 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3920
3921 // Check for parameter type matching.
3922 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3923 QualType ArgType = CtorType->getArgType(0);
3924 if (ArgType->getPointeeType().isVolatileQualified()) {
3925 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3926 HadError = true;
3927 }
3928 if (ArgType->getPointeeType().isConstQualified()) {
3929 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3930 HadError = true;
3931 }
3932
3933 if (CtorType->hasExceptionSpec()) {
3934 if (CheckEquivalentExceptionSpec(
3935 PDiag(diag::err_incorrect_defaulted_exception_spec)
3936 << CXXMoveConstructor,
3937 PDiag(),
3938 ExceptionType, SourceLocation(),
3939 CtorType, CD->getLocation())) {
3940 HadError = true;
3941 }
3942 } else if (First) {
3943 // We set the declaration to have the computed exception spec here.
3944 // We duplicate the one parameter type.
3945 EPI.ExtInfo = CtorType->getExtInfo();
3946 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3947 }
3948
3949 if (HadError) {
3950 CD->setInvalidDecl();
3951 return;
3952 }
3953
3954 if (ShouldDeleteMoveConstructor(CD)) {
3955 if (First) {
3956 CD->setDeletedAsWritten();
3957 } else {
3958 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3959 << CXXMoveConstructor;
3960 CD->setInvalidDecl();
3961 }
3962 }
3963}
3964
3965void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3966 assert(MD->isExplicitlyDefaulted());
3967
3968 // Whether this was the first-declared instance of the operator
3969 bool First = MD == MD->getCanonicalDecl();
3970
3971 bool HadError = false;
3972 if (MD->getNumParams() != 1) {
3973 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3974 << MD->getSourceRange();
3975 HadError = true;
3976 }
3977
3978 QualType ReturnType =
3979 MD->getType()->getAs<FunctionType>()->getResultType();
3980 if (!ReturnType->isLValueReferenceType() ||
3981 !Context.hasSameType(
3982 Context.getCanonicalType(ReturnType->getPointeeType()),
3983 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3984 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3985 HadError = true;
3986 }
3987
3988 ImplicitExceptionSpecification Spec(
3989 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3990
3991 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3992 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3993 *ExceptionType = Context.getFunctionType(
3994 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3995
3996 QualType ArgType = OperType->getArgType(0);
3997 if (!ArgType->isRValueReferenceType()) {
3998 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3999 HadError = true;
4000 } else {
4001 if (ArgType->getPointeeType().isVolatileQualified()) {
4002 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4003 HadError = true;
4004 }
4005 if (ArgType->getPointeeType().isConstQualified()) {
4006 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4007 HadError = true;
4008 }
4009 }
4010
4011 if (OperType->getTypeQuals()) {
4012 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4013 HadError = true;
4014 }
4015
4016 if (OperType->hasExceptionSpec()) {
4017 if (CheckEquivalentExceptionSpec(
4018 PDiag(diag::err_incorrect_defaulted_exception_spec)
4019 << CXXMoveAssignment,
4020 PDiag(),
4021 ExceptionType, SourceLocation(),
4022 OperType, MD->getLocation())) {
4023 HadError = true;
4024 }
4025 } else if (First) {
4026 // We set the declaration to have the computed exception spec here.
4027 // We duplicate the one parameter type.
4028 EPI.RefQualifier = OperType->getRefQualifier();
4029 EPI.ExtInfo = OperType->getExtInfo();
4030 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4031 }
4032
4033 if (HadError) {
4034 MD->setInvalidDecl();
4035 return;
4036 }
4037
4038 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4039 if (First) {
4040 MD->setDeletedAsWritten();
4041 } else {
4042 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4043 << CXXMoveAssignment;
4044 MD->setInvalidDecl();
4045 }
4046 }
4047}
4048
Alexis Huntf91729462011-05-12 22:46:25 +00004049void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4050 assert(DD->isExplicitlyDefaulted());
4051
4052 // Whether this was the first-declared instance of the destructor.
4053 bool First = DD == DD->getCanonicalDecl();
4054
4055 ImplicitExceptionSpecification Spec
4056 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4057 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4058 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4059 *ExceptionType = Context.getFunctionType(
4060 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4061
4062 if (DtorType->hasExceptionSpec()) {
4063 if (CheckEquivalentExceptionSpec(
4064 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004065 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00004066 PDiag(),
4067 ExceptionType, SourceLocation(),
4068 DtorType, DD->getLocation())) {
4069 DD->setInvalidDecl();
4070 return;
4071 }
4072 } else if (First) {
4073 // We set the declaration to have the computed exception spec here.
4074 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00004075 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00004076 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4077 }
4078
4079 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00004080 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004081 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00004082 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00004083 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004084 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00004085 DD->setInvalidDecl();
4086 }
Alexis Huntf91729462011-05-12 22:46:25 +00004087 }
Alexis Huntf91729462011-05-12 22:46:25 +00004088}
4089
Alexis Huntd6da8762011-10-10 06:18:57 +00004090/// This function implements the following C++0x paragraphs:
4091/// - [class.ctor]/5
4092bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4093 assert(!MD->isInvalidDecl());
4094 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00004095 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004096 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004097 return false;
4098
Alexis Huntd6da8762011-10-10 06:18:57 +00004099 bool IsUnion = RD->isUnion();
4100 bool IsConstructor = false;
4101 bool IsAssignment = false;
4102 bool IsMove = false;
4103
4104 bool ConstArg = false;
4105
4106 switch (CSM) {
4107 case CXXDefaultConstructor:
4108 IsConstructor = true;
4109 break;
4110 default:
4111 llvm_unreachable("function only currently implemented for default ctors");
4112 }
4113
4114 SourceLocation Loc = MD->getLocation();
Alexis Hunte77a28f2011-05-18 03:41:58 +00004115
Alexis Huntea6f0322011-05-11 22:34:38 +00004116 // Do access control from the constructor
Alexis Huntd6da8762011-10-10 06:18:57 +00004117 ContextRAII MethodContext(*this, MD);
Alexis Huntea6f0322011-05-11 22:34:38 +00004118
Alexis Huntea6f0322011-05-11 22:34:38 +00004119 bool AllConst = true;
4120
Alexis Huntea6f0322011-05-11 22:34:38 +00004121 // We do this because we should never actually use an anonymous
4122 // union's constructor.
Alexis Huntd6da8762011-10-10 06:18:57 +00004123 if (IsUnion && RD->isAnonymousStructOrUnion())
Alexis Huntea6f0322011-05-11 22:34:38 +00004124 return false;
4125
4126 // FIXME: We should put some diagnostic logic right into this function.
4127
Alexis Huntea6f0322011-05-11 22:34:38 +00004128 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4129 BE = RD->bases_end();
4130 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00004131 // We'll handle this one later
4132 if (BI->isVirtual())
4133 continue;
4134
Alexis Huntea6f0322011-05-11 22:34:38 +00004135 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4136 assert(BaseDecl && "base isn't a CXXRecordDecl");
4137
Alexis Huntd6da8762011-10-10 06:18:57 +00004138 // Unless we have an assignment operator, the base's destructor must
4139 // be accessible and not deleted.
4140 if (!IsAssignment) {
4141 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4142 if (BaseDtor->isDeleted())
4143 return true;
4144 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4145 AR_accessible)
4146 return true;
4147 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004148
Alexis Huntd6da8762011-10-10 06:18:57 +00004149 // Finding the corresponding member in the base should lead to a
4150 // unique, accessible, non-deleted function.
4151 if (CSM != CXXDestructor) {
4152 SpecialMemberOverloadResult *SMOR =
4153 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, IsMove, false,
4154 false);
4155 if (!SMOR->hasSuccess())
4156 return true;
4157 CXXMethodDecl *BaseMember = SMOR->getMethod();
4158 if (IsConstructor) {
4159 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4160 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4161 PDiag()) != AR_accessible)
4162 return true;
4163 }
4164 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004165 }
4166
4167 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4168 BE = RD->vbases_end();
4169 BI != BE; ++BI) {
4170 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4171 assert(BaseDecl && "base isn't a CXXRecordDecl");
4172
Alexis Huntd6da8762011-10-10 06:18:57 +00004173 // Unless we have an assignment operator, the base's destructor must
4174 // be accessible and not deleted.
4175 if (!IsAssignment) {
4176 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4177 if (BaseDtor->isDeleted())
4178 return true;
4179 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4180 AR_accessible)
4181 return true;
4182 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004183
Alexis Huntd6da8762011-10-10 06:18:57 +00004184 // Finding the corresponding member in the base should lead to a
4185 // unique, accessible, non-deleted function.
4186 if (CSM != CXXDestructor) {
4187 SpecialMemberOverloadResult *SMOR =
4188 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, IsMove, false,
4189 false);
4190 if (!SMOR->hasSuccess())
4191 return true;
4192 CXXMethodDecl *BaseMember = SMOR->getMethod();
4193 if (IsConstructor) {
4194 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4195 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4196 PDiag()) != AR_accessible)
4197 return true;
4198 }
4199 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004200 }
4201
4202 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4203 FE = RD->field_end();
4204 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00004205 if (FI->isInvalidDecl())
4206 continue;
4207
Alexis Huntea6f0322011-05-11 22:34:38 +00004208 QualType FieldType = Context.getBaseElementType(FI->getType());
4209 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00004210
Alexis Huntd6da8762011-10-10 06:18:57 +00004211 // For a default constructor, all references must be initialized in-class
4212 // and, if a union, it must have a non-const member.
4213 if (CSM == CXXDefaultConstructor) {
4214 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4215 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004216
Alexis Huntd6da8762011-10-10 06:18:57 +00004217 if (IsUnion && !FieldType.isConstQualified())
4218 AllConst = false;
4219 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004220
4221 if (FieldRecord) {
Alexis Huntd6da8762011-10-10 06:18:57 +00004222 // Unless we're doing assignment, the field's destructor must be
4223 // accessible and not deleted.
4224 if (!IsAssignment) {
4225 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4226 if (FieldDtor->isDeleted())
4227 return true;
4228 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4229 AR_accessible)
4230 return true;
4231 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004232
Alexis Huntd6da8762011-10-10 06:18:57 +00004233 // For a default constructor, a const member must have a user-provided
4234 // default constructor or else be explicitly initialized.
4235 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00004236 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004237 !FieldRecord->hasUserProvidedDefaultConstructor())
4238 return true;
4239
Alexis Huntd6da8762011-10-10 06:18:57 +00004240 // For a default constructor, additional restrictions exist on the
4241 // variant members.
4242 if (CSM == CXXDefaultConstructor && !IsUnion && FieldRecord->isUnion() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004243 FieldRecord->isAnonymousStructOrUnion()) {
4244 // We're okay to reuse AllConst here since we only care about the
4245 // value otherwise if we're in a union.
4246 AllConst = true;
4247
4248 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4249 UE = FieldRecord->field_end();
4250 UI != UE; ++UI) {
4251 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4252 CXXRecordDecl *UnionFieldRecord =
4253 UnionFieldType->getAsCXXRecordDecl();
4254
4255 if (!UnionFieldType.isConstQualified())
4256 AllConst = false;
4257
4258 if (UnionFieldRecord &&
4259 !UnionFieldRecord->hasTrivialDefaultConstructor())
4260 return true;
4261 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00004262
Alexis Huntea6f0322011-05-11 22:34:38 +00004263 if (AllConst)
4264 return true;
4265
4266 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00004267 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00004268 continue;
4269 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00004270
Alexis Huntd6da8762011-10-10 06:18:57 +00004271 // Check that the corresponding member of the field is accessible,
4272 // unique, and non-deleted. We don't do this if it has an explicit
4273 // initialization when default-constructing.
4274 if (CSM != CXXDestructor &&
4275 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4276 SpecialMemberOverloadResult *SMOR =
4277 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, IsMove, false,
4278 false);
4279 if (!SMOR->hasSuccess())
Richard Smith938f40b2011-06-11 17:19:42 +00004280 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004281
4282 CXXMethodDecl *FieldMember = SMOR->getMethod();
4283 if (IsConstructor) {
4284 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4285 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4286 PDiag()) != AR_accessible)
4287 return true;
4288 }
4289
4290 // We need the corresponding member of a union to be trivial so that
4291 // we can safely copy them all simultaneously.
4292 // FIXME: Note that performing the check here (where we rely on the lack
4293 // of an in-class initializer) is technically ill-formed. However, this
4294 // seems most obviously to be a bug in the standard.
4295 if (IsUnion && !FieldMember->isTrivial())
Richard Smith938f40b2011-06-11 17:19:42 +00004296 return true;
4297 }
Alexis Huntd6da8762011-10-10 06:18:57 +00004298 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4299 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4300 // We can't initialize a const member of non-class type to any value.
Alexis Hunta671bca2011-05-20 21:43:47 +00004301 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004302 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004303 }
4304
Alexis Huntd6da8762011-10-10 06:18:57 +00004305 // We can't have all const members in a union when default-constructing,
4306 // or else they're all nonsensical garbage values that can't be changed.
4307 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004308 return true;
4309
4310 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004311}
4312
Alexis Hunt913820d2011-05-13 06:10:58 +00004313bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00004314 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00004315 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004316 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Hunt913820d2011-05-13 06:10:58 +00004317 return false;
4318
Alexis Hunte77a28f2011-05-18 03:41:58 +00004319 SourceLocation Loc = CD->getLocation();
4320
Alexis Hunt913820d2011-05-13 06:10:58 +00004321 // Do access control from the constructor
4322 ContextRAII CtorContext(*this, CD);
4323
Alexis Hunt899bd442011-06-10 04:44:37 +00004324 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00004325
Alexis Huntc9a55732011-05-14 05:23:28 +00004326 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4327 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00004328 unsigned ArgQuals =
4329 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4330 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00004331
4332 // We do this because we should never actually use an anonymous
4333 // union's constructor.
4334 if (Union && RD->isAnonymousStructOrUnion())
4335 return false;
4336
4337 // FIXME: We should put some diagnostic logic right into this function.
4338
4339 // C++0x [class.copy]/11
4340 // A defaulted [copy] constructor for class X is defined as delete if X has:
4341
4342 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4343 BE = RD->bases_end();
4344 BI != BE; ++BI) {
4345 // We'll handle this one later
4346 if (BI->isVirtual())
4347 continue;
4348
4349 QualType BaseType = BI->getType();
4350 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4351 assert(BaseDecl && "base isn't a CXXRecordDecl");
4352
4353 // -- any [direct base class] of a type with a destructor that is deleted or
4354 // inaccessible from the defaulted constructor
4355 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4356 if (BaseDtor->isDeleted())
4357 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004358 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00004359 AR_accessible)
4360 return true;
4361
4362 // -- a [direct base class] B that cannot be [copied] because overload
4363 // resolution, as applied to B's [copy] constructor, results in an
4364 // ambiguity or a function that is deleted or inaccessible from the
4365 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00004366 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004367 if (!BaseCtor || BaseCtor->isDeleted())
4368 return true;
4369 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4370 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00004371 return true;
4372 }
4373
4374 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4375 BE = RD->vbases_end();
4376 BI != BE; ++BI) {
4377 QualType BaseType = BI->getType();
4378 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4379 assert(BaseDecl && "base isn't a CXXRecordDecl");
4380
Alexis Hunteef8ee02011-06-10 03:50:41 +00004381 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00004382 // inaccessible from the defaulted constructor
4383 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4384 if (BaseDtor->isDeleted())
4385 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004386 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00004387 AR_accessible)
4388 return true;
4389
4390 // -- a [virtual base class] B that cannot be [copied] because overload
4391 // resolution, as applied to B's [copy] constructor, results in an
4392 // ambiguity or a function that is deleted or inaccessible from the
4393 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00004394 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004395 if (!BaseCtor || BaseCtor->isDeleted())
4396 return true;
4397 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4398 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00004399 return true;
4400 }
4401
4402 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4403 FE = RD->field_end();
4404 FI != FE; ++FI) {
4405 QualType FieldType = Context.getBaseElementType(FI->getType());
4406
4407 // -- for a copy constructor, a non-static data member of rvalue reference
4408 // type
4409 if (FieldType->isRValueReferenceType())
4410 return true;
4411
4412 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4413
4414 if (FieldRecord) {
4415 // This is an anonymous union
4416 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4417 // Anonymous unions inside unions do not variant members create
4418 if (!Union) {
4419 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4420 UE = FieldRecord->field_end();
4421 UI != UE; ++UI) {
4422 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4423 CXXRecordDecl *UnionFieldRecord =
4424 UnionFieldType->getAsCXXRecordDecl();
4425
4426 // -- a variant member with a non-trivial [copy] constructor and X
4427 // is a union-like class
4428 if (UnionFieldRecord &&
4429 !UnionFieldRecord->hasTrivialCopyConstructor())
4430 return true;
4431 }
4432 }
4433
4434 // Don't try to initalize an anonymous union
4435 continue;
4436 } else {
4437 // -- a variant member with a non-trivial [copy] constructor and X is a
4438 // union-like class
4439 if (Union && !FieldRecord->hasTrivialCopyConstructor())
4440 return true;
4441
4442 // -- any [non-static data member] of a type with a destructor that is
4443 // deleted or inaccessible from the defaulted constructor
4444 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4445 if (FieldDtor->isDeleted())
4446 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004447 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00004448 AR_accessible)
4449 return true;
4450 }
Alexis Hunt899bd442011-06-10 04:44:37 +00004451
4452 // -- a [non-static data member of class type (or array thereof)] B that
4453 // cannot be [copied] because overload resolution, as applied to B's
4454 // [copy] constructor, results in an ambiguity or a function that is
4455 // deleted or inaccessible from the defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00004456 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4457 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004458 if (!FieldCtor || FieldCtor->isDeleted())
4459 return true;
4460 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4461 PDiag()) != AR_accessible)
4462 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00004463 }
Alexis Hunt913820d2011-05-13 06:10:58 +00004464 }
4465
4466 return false;
4467}
4468
Alexis Huntb2f27802011-05-14 05:23:24 +00004469bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4470 CXXRecordDecl *RD = MD->getParent();
4471 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004472 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004473 return false;
4474
Alexis Hunte77a28f2011-05-18 03:41:58 +00004475 SourceLocation Loc = MD->getLocation();
4476
Alexis Huntb2f27802011-05-14 05:23:24 +00004477 // Do access control from the constructor
4478 ContextRAII MethodContext(*this, MD);
4479
4480 bool Union = RD->isUnion();
4481
Alexis Hunt491ec602011-06-21 23:42:56 +00004482 unsigned ArgQuals =
4483 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4484 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004485
4486 // We do this because we should never actually use an anonymous
4487 // union's constructor.
4488 if (Union && RD->isAnonymousStructOrUnion())
4489 return false;
4490
Alexis Huntb2f27802011-05-14 05:23:24 +00004491 // FIXME: We should put some diagnostic logic right into this function.
4492
Sebastian Redl22653ba2011-08-30 19:58:05 +00004493 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004494 // A defaulted [copy] assignment operator for class X is defined as deleted
4495 // if X has:
4496
4497 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4498 BE = RD->bases_end();
4499 BI != BE; ++BI) {
4500 // We'll handle this one later
4501 if (BI->isVirtual())
4502 continue;
4503
4504 QualType BaseType = BI->getType();
4505 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4506 assert(BaseDecl && "base isn't a CXXRecordDecl");
4507
4508 // -- a [direct base class] B that cannot be [copied] because overload
4509 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004510 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004511 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004512 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4513 0);
4514 if (!CopyOper || CopyOper->isDeleted())
4515 return true;
4516 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004517 return true;
4518 }
4519
4520 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4521 BE = RD->vbases_end();
4522 BI != BE; ++BI) {
4523 QualType BaseType = BI->getType();
4524 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4525 assert(BaseDecl && "base isn't a CXXRecordDecl");
4526
Alexis Huntb2f27802011-05-14 05:23:24 +00004527 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004528 // resolution, as applied to B's [copy] assignment operator, results in
4529 // an ambiguity or a function that is deleted or inaccessible from the
4530 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004531 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4532 0);
4533 if (!CopyOper || CopyOper->isDeleted())
4534 return true;
4535 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004536 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004537 }
4538
4539 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4540 FE = RD->field_end();
4541 FI != FE; ++FI) {
4542 QualType FieldType = Context.getBaseElementType(FI->getType());
4543
4544 // -- a non-static data member of reference type
4545 if (FieldType->isReferenceType())
4546 return true;
4547
4548 // -- a non-static data member of const non-class type (or array thereof)
4549 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4550 return true;
4551
4552 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4553
4554 if (FieldRecord) {
4555 // This is an anonymous union
4556 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4557 // Anonymous unions inside unions do not variant members create
4558 if (!Union) {
4559 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4560 UE = FieldRecord->field_end();
4561 UI != UE; ++UI) {
4562 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4563 CXXRecordDecl *UnionFieldRecord =
4564 UnionFieldType->getAsCXXRecordDecl();
4565
4566 // -- a variant member with a non-trivial [copy] assignment operator
4567 // and X is a union-like class
4568 if (UnionFieldRecord &&
4569 !UnionFieldRecord->hasTrivialCopyAssignment())
4570 return true;
4571 }
4572 }
4573
4574 // Don't try to initalize an anonymous union
4575 continue;
4576 // -- a variant member with a non-trivial [copy] assignment operator
4577 // and X is a union-like class
4578 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4579 return true;
4580 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004581
Alexis Hunt491ec602011-06-21 23:42:56 +00004582 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4583 false, 0);
4584 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004585 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004586 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004587 return true;
4588 }
4589 }
4590
4591 return false;
4592}
4593
4594bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4595 CXXRecordDecl *RD = CD->getParent();
4596 assert(!RD->isDependentType() && "do deletion after instantiation");
4597 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4598 return false;
4599
4600 SourceLocation Loc = CD->getLocation();
4601
4602 // Do access control from the constructor
4603 ContextRAII CtorContext(*this, CD);
4604
4605 bool Union = RD->isUnion();
4606
4607 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4608 "copy assignment arg has no pointee type");
4609
4610 // We do this because we should never actually use an anonymous
4611 // union's constructor.
4612 if (Union && RD->isAnonymousStructOrUnion())
4613 return false;
4614
4615 // C++0x [class.copy]/11
4616 // A defaulted [move] constructor for class X is defined as deleted
4617 // if X has:
4618
4619 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4620 BE = RD->bases_end();
4621 BI != BE; ++BI) {
4622 // We'll handle this one later
4623 if (BI->isVirtual())
4624 continue;
4625
4626 QualType BaseType = BI->getType();
4627 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4628 assert(BaseDecl && "base isn't a CXXRecordDecl");
4629
4630 // -- any [direct base class] of a type with a destructor that is deleted or
4631 // inaccessible from the defaulted constructor
4632 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4633 if (BaseDtor->isDeleted())
4634 return true;
4635 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4636 AR_accessible)
4637 return true;
4638
4639 // -- a [direct base class] B that cannot be [moved] because overload
4640 // resolution, as applied to B's [move] constructor, results in an
4641 // ambiguity or a function that is deleted or inaccessible from the
4642 // defaulted constructor
4643 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4644 if (!BaseCtor || BaseCtor->isDeleted())
4645 return true;
4646 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4647 AR_accessible)
4648 return true;
4649
4650 // -- for a move constructor, a [direct base class] with a type that
4651 // does not have a move constructor and is not trivially copyable.
4652 // If the field isn't a record, it's always trivially copyable.
4653 // A moving constructor could be a copy constructor instead.
4654 if (!BaseCtor->isMoveConstructor() &&
4655 !BaseDecl->isTriviallyCopyable())
4656 return true;
4657 }
4658
4659 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4660 BE = RD->vbases_end();
4661 BI != BE; ++BI) {
4662 QualType BaseType = BI->getType();
4663 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4664 assert(BaseDecl && "base isn't a CXXRecordDecl");
4665
4666 // -- any [virtual base class] of a type with a destructor that is deleted
4667 // or inaccessible from the defaulted constructor
4668 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4669 if (BaseDtor->isDeleted())
4670 return true;
4671 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4672 AR_accessible)
4673 return true;
4674
4675 // -- a [virtual base class] B that cannot be [moved] because overload
4676 // resolution, as applied to B's [move] constructor, results in an
4677 // ambiguity or a function that is deleted or inaccessible from the
4678 // defaulted constructor
4679 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4680 if (!BaseCtor || BaseCtor->isDeleted())
4681 return true;
4682 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4683 AR_accessible)
4684 return true;
4685
4686 // -- for a move constructor, a [virtual base class] with a type that
4687 // does not have a move constructor and is not trivially copyable.
4688 // If the field isn't a record, it's always trivially copyable.
4689 // A moving constructor could be a copy constructor instead.
4690 if (!BaseCtor->isMoveConstructor() &&
4691 !BaseDecl->isTriviallyCopyable())
4692 return true;
4693 }
4694
4695 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4696 FE = RD->field_end();
4697 FI != FE; ++FI) {
4698 QualType FieldType = Context.getBaseElementType(FI->getType());
4699
4700 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4701 // This is an anonymous union
4702 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4703 // Anonymous unions inside unions do not variant members create
4704 if (!Union) {
4705 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4706 UE = FieldRecord->field_end();
4707 UI != UE; ++UI) {
4708 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4709 CXXRecordDecl *UnionFieldRecord =
4710 UnionFieldType->getAsCXXRecordDecl();
4711
4712 // -- a variant member with a non-trivial [move] constructor and X
4713 // is a union-like class
4714 if (UnionFieldRecord &&
4715 !UnionFieldRecord->hasTrivialMoveConstructor())
4716 return true;
4717 }
4718 }
4719
4720 // Don't try to initalize an anonymous union
4721 continue;
4722 } else {
4723 // -- a variant member with a non-trivial [move] constructor and X is a
4724 // union-like class
4725 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4726 return true;
4727
4728 // -- any [non-static data member] of a type with a destructor that is
4729 // deleted or inaccessible from the defaulted constructor
4730 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4731 if (FieldDtor->isDeleted())
4732 return true;
4733 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4734 AR_accessible)
4735 return true;
4736 }
4737
4738 // -- a [non-static data member of class type (or array thereof)] B that
4739 // cannot be [moved] because overload resolution, as applied to B's
4740 // [move] constructor, results in an ambiguity or a function that is
4741 // deleted or inaccessible from the defaulted constructor
4742 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4743 if (!FieldCtor || FieldCtor->isDeleted())
4744 return true;
4745 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4746 PDiag()) != AR_accessible)
4747 return true;
4748
4749 // -- for a move constructor, a [non-static data member] with a type that
4750 // does not have a move constructor and is not trivially copyable.
4751 // If the field isn't a record, it's always trivially copyable.
4752 // A moving constructor could be a copy constructor instead.
4753 if (!FieldCtor->isMoveConstructor() &&
4754 !FieldRecord->isTriviallyCopyable())
4755 return true;
4756 }
4757 }
4758
4759 return false;
4760}
4761
4762bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4763 CXXRecordDecl *RD = MD->getParent();
4764 assert(!RD->isDependentType() && "do deletion after instantiation");
4765 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4766 return false;
4767
4768 SourceLocation Loc = MD->getLocation();
4769
4770 // Do access control from the constructor
4771 ContextRAII MethodContext(*this, MD);
4772
4773 bool Union = RD->isUnion();
4774
4775 // We do this because we should never actually use an anonymous
4776 // union's constructor.
4777 if (Union && RD->isAnonymousStructOrUnion())
4778 return false;
4779
4780 // C++0x [class.copy]/20
4781 // A defaulted [move] assignment operator for class X is defined as deleted
4782 // if X has:
4783
4784 // -- for the move constructor, [...] any direct or indirect virtual base
4785 // class.
4786 if (RD->getNumVBases() != 0)
4787 return true;
4788
4789 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4790 BE = RD->bases_end();
4791 BI != BE; ++BI) {
4792
4793 QualType BaseType = BI->getType();
4794 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4795 assert(BaseDecl && "base isn't a CXXRecordDecl");
4796
4797 // -- a [direct base class] B that cannot be [moved] because overload
4798 // resolution, as applied to B's [move] assignment operator, results in
4799 // an ambiguity or a function that is deleted or inaccessible from the
4800 // assignment operator
4801 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4802 if (!MoveOper || MoveOper->isDeleted())
4803 return true;
4804 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4805 return true;
4806
4807 // -- for the move assignment operator, a [direct base class] with a type
4808 // that does not have a move assignment operator and is not trivially
4809 // copyable.
4810 if (!MoveOper->isMoveAssignmentOperator() &&
4811 !BaseDecl->isTriviallyCopyable())
4812 return true;
4813 }
4814
4815 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4816 FE = RD->field_end();
4817 FI != FE; ++FI) {
4818 QualType FieldType = Context.getBaseElementType(FI->getType());
4819
4820 // -- a non-static data member of reference type
4821 if (FieldType->isReferenceType())
4822 return true;
4823
4824 // -- a non-static data member of const non-class type (or array thereof)
4825 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4826 return true;
4827
4828 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4829
4830 if (FieldRecord) {
4831 // This is an anonymous union
4832 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4833 // Anonymous unions inside unions do not variant members create
4834 if (!Union) {
4835 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4836 UE = FieldRecord->field_end();
4837 UI != UE; ++UI) {
4838 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4839 CXXRecordDecl *UnionFieldRecord =
4840 UnionFieldType->getAsCXXRecordDecl();
4841
4842 // -- a variant member with a non-trivial [move] assignment operator
4843 // and X is a union-like class
4844 if (UnionFieldRecord &&
4845 !UnionFieldRecord->hasTrivialMoveAssignment())
4846 return true;
4847 }
4848 }
4849
4850 // Don't try to initalize an anonymous union
4851 continue;
4852 // -- a variant member with a non-trivial [move] assignment operator
4853 // and X is a union-like class
4854 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4855 return true;
4856 }
4857
4858 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4859 if (!MoveOper || MoveOper->isDeleted())
4860 return true;
4861 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4862 return true;
4863
4864 // -- for the move assignment operator, a [non-static data member] with a
4865 // type that does not have a move assignment operator and is not
4866 // trivially copyable.
4867 if (!MoveOper->isMoveAssignmentOperator() &&
4868 !FieldRecord->isTriviallyCopyable())
4869 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004870 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004871 }
4872
4873 return false;
4874}
4875
Alexis Huntf91729462011-05-12 22:46:25 +00004876bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4877 CXXRecordDecl *RD = DD->getParent();
4878 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004879 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004880 return false;
4881
Alexis Hunte77a28f2011-05-18 03:41:58 +00004882 SourceLocation Loc = DD->getLocation();
4883
Alexis Huntf91729462011-05-12 22:46:25 +00004884 // Do access control from the destructor
4885 ContextRAII CtorContext(*this, DD);
4886
4887 bool Union = RD->isUnion();
4888
Alexis Hunt913820d2011-05-13 06:10:58 +00004889 // We do this because we should never actually use an anonymous
4890 // union's destructor.
4891 if (Union && RD->isAnonymousStructOrUnion())
4892 return false;
4893
Alexis Huntf91729462011-05-12 22:46:25 +00004894 // C++0x [class.dtor]p5
4895 // A defaulted destructor for a class X is defined as deleted if:
4896 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4897 BE = RD->bases_end();
4898 BI != BE; ++BI) {
4899 // We'll handle this one later
4900 if (BI->isVirtual())
4901 continue;
4902
4903 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4904 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4905 assert(BaseDtor && "base has no destructor");
4906
4907 // -- any direct or virtual base class has a deleted destructor or
4908 // a destructor that is inaccessible from the defaulted destructor
4909 if (BaseDtor->isDeleted())
4910 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004911 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004912 AR_accessible)
4913 return true;
4914 }
4915
4916 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4917 BE = RD->vbases_end();
4918 BI != BE; ++BI) {
4919 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4920 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4921 assert(BaseDtor && "base has no destructor");
4922
4923 // -- any direct or virtual base class has a deleted destructor or
4924 // a destructor that is inaccessible from the defaulted destructor
4925 if (BaseDtor->isDeleted())
4926 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004927 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004928 AR_accessible)
4929 return true;
4930 }
4931
4932 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4933 FE = RD->field_end();
4934 FI != FE; ++FI) {
4935 QualType FieldType = Context.getBaseElementType(FI->getType());
4936 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4937 if (FieldRecord) {
4938 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4939 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4940 UE = FieldRecord->field_end();
4941 UI != UE; ++UI) {
4942 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4943 CXXRecordDecl *UnionFieldRecord =
4944 UnionFieldType->getAsCXXRecordDecl();
4945
4946 // -- X is a union-like class that has a variant member with a non-
4947 // trivial destructor.
4948 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4949 return true;
4950 }
4951 // Technically we are supposed to do this next check unconditionally.
4952 // But that makes absolutely no sense.
4953 } else {
4954 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4955
4956 // -- any of the non-static data members has class type M (or array
4957 // thereof) and M has a deleted destructor or a destructor that is
4958 // inaccessible from the defaulted destructor
4959 if (FieldDtor->isDeleted())
4960 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004961 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004962 AR_accessible)
4963 return true;
4964
4965 // -- X is a union-like class that has a variant member with a non-
4966 // trivial destructor.
4967 if (Union && !FieldDtor->isTrivial())
4968 return true;
4969 }
4970 }
4971 }
4972
4973 if (DD->isVirtual()) {
4974 FunctionDecl *OperatorDelete = 0;
4975 DeclarationName Name =
4976 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004977 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004978 false))
4979 return true;
4980 }
4981
4982
4983 return false;
4984}
4985
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004986/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004987namespace {
4988 struct FindHiddenVirtualMethodData {
4989 Sema *S;
4990 CXXMethodDecl *Method;
4991 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004992 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004993 };
4994}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004995
4996/// \brief Member lookup function that determines whether a given C++
4997/// method overloads virtual methods in a base class without overriding any,
4998/// to be used with CXXRecordDecl::lookupInBases().
4999static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5000 CXXBasePath &Path,
5001 void *UserData) {
5002 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5003
5004 FindHiddenVirtualMethodData &Data
5005 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5006
5007 DeclarationName Name = Data.Method->getDeclName();
5008 assert(Name.getNameKind() == DeclarationName::Identifier);
5009
5010 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005011 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005012 for (Path.Decls = BaseRecord->lookup(Name);
5013 Path.Decls.first != Path.Decls.second;
5014 ++Path.Decls.first) {
5015 NamedDecl *D = *Path.Decls.first;
5016 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005017 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005018 foundSameNameMethod = true;
5019 // Interested only in hidden virtual methods.
5020 if (!MD->isVirtual())
5021 continue;
5022 // If the method we are checking overrides a method from its base
5023 // don't warn about the other overloaded methods.
5024 if (!Data.S->IsOverload(Data.Method, MD, false))
5025 return true;
5026 // Collect the overload only if its hidden.
5027 if (!Data.OverridenAndUsingBaseMethods.count(MD))
5028 overloadedMethods.push_back(MD);
5029 }
5030 }
5031
5032 if (foundSameNameMethod)
5033 Data.OverloadedMethods.append(overloadedMethods.begin(),
5034 overloadedMethods.end());
5035 return foundSameNameMethod;
5036}
5037
5038/// \brief See if a method overloads virtual methods in a base class without
5039/// overriding any.
5040void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5041 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00005042 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005043 return;
5044 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5045 return;
5046
5047 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5048 /*bool RecordPaths=*/false,
5049 /*bool DetectVirtual=*/false);
5050 FindHiddenVirtualMethodData Data;
5051 Data.Method = MD;
5052 Data.S = this;
5053
5054 // Keep the base methods that were overriden or introduced in the subclass
5055 // by 'using' in a set. A base method not in this set is hidden.
5056 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5057 res.first != res.second; ++res.first) {
5058 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5059 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5060 E = MD->end_overridden_methods();
5061 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005062 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005063 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5064 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005065 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005066 }
5067
5068 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5069 !Data.OverloadedMethods.empty()) {
5070 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5071 << MD << (Data.OverloadedMethods.size() > 1);
5072
5073 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5074 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5075 Diag(overloadedMD->getLocation(),
5076 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5077 }
5078 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005079}
5080
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005081void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005082 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005083 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005084 SourceLocation RBrac,
5085 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005086 if (!TagDecl)
5087 return;
Mike Stump11289f42009-09-09 15:08:12 +00005088
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005089 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005090
David Blaikie751c5582011-09-22 02:58:26 +00005091 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005092 // strict aliasing violation!
5093 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005094 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005095
Douglas Gregor0be31a22010-07-02 17:43:08 +00005096 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005097 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005098}
5099
Douglas Gregor05379422008-11-03 17:51:48 +00005100/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5101/// special functions, such as the default constructor, copy
5102/// constructor, or destructor, to the given C++ class (C++
5103/// [special]p1). This routine can only be executed just before the
5104/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005105void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005106 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005107 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005108
Douglas Gregor54be3392010-07-01 17:57:27 +00005109 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00005110 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005111
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005112 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5113 ++ASTContext::NumImplicitCopyAssignmentOperators;
5114
5115 // If we have a dynamic class, then the copy assignment operator may be
5116 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5117 // it shows up in the right place in the vtable and that we diagnose
5118 // problems with the implicit exception specification.
5119 if (ClassDecl->isDynamicClass())
5120 DeclareImplicitCopyAssignment(ClassDecl);
5121 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005122
Douglas Gregor7454c562010-07-02 20:37:36 +00005123 if (!ClassDecl->hasUserDeclaredDestructor()) {
5124 ++ASTContext::NumImplicitDestructors;
5125
5126 // If we have a dynamic class, then the destructor may be virtual, so we
5127 // have to declare the destructor immediately. This ensures that, e.g., it
5128 // shows up in the right place in the vtable and that we diagnose problems
5129 // with the implicit exception specification.
5130 if (ClassDecl->isDynamicClass())
5131 DeclareImplicitDestructor(ClassDecl);
5132 }
Douglas Gregor05379422008-11-03 17:51:48 +00005133}
5134
Francois Pichet1c229c02011-04-22 22:18:13 +00005135void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5136 if (!D)
5137 return;
5138
5139 int NumParamList = D->getNumTemplateParameterLists();
5140 for (int i = 0; i < NumParamList; i++) {
5141 TemplateParameterList* Params = D->getTemplateParameterList(i);
5142 for (TemplateParameterList::iterator Param = Params->begin(),
5143 ParamEnd = Params->end();
5144 Param != ParamEnd; ++Param) {
5145 NamedDecl *Named = cast<NamedDecl>(*Param);
5146 if (Named->getDeclName()) {
5147 S->AddDecl(Named);
5148 IdResolver.AddDecl(Named);
5149 }
5150 }
5151 }
5152}
5153
John McCall48871652010-08-21 09:40:31 +00005154void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005155 if (!D)
5156 return;
5157
5158 TemplateParameterList *Params = 0;
5159 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5160 Params = Template->getTemplateParameters();
5161 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5162 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5163 Params = PartialSpec->getTemplateParameters();
5164 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005165 return;
5166
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005167 for (TemplateParameterList::iterator Param = Params->begin(),
5168 ParamEnd = Params->end();
5169 Param != ParamEnd; ++Param) {
5170 NamedDecl *Named = cast<NamedDecl>(*Param);
5171 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005172 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005173 IdResolver.AddDecl(Named);
5174 }
5175 }
5176}
5177
John McCall48871652010-08-21 09:40:31 +00005178void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005179 if (!RecordD) return;
5180 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005181 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005182 PushDeclContext(S, Record);
5183}
5184
John McCall48871652010-08-21 09:40:31 +00005185void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005186 if (!RecordD) return;
5187 PopDeclContext();
5188}
5189
Douglas Gregor4d87df52008-12-16 21:30:33 +00005190/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5191/// parsing a top-level (non-nested) C++ class, and we are now
5192/// parsing those parts of the given Method declaration that could
5193/// not be parsed earlier (C++ [class.mem]p2), such as default
5194/// arguments. This action should enter the scope of the given
5195/// Method declaration as if we had just parsed the qualified method
5196/// name. However, it should not bring the parameters into scope;
5197/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005198void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005199}
5200
5201/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5202/// C++ method declaration. We're (re-)introducing the given
5203/// function parameter into scope for use in parsing later parts of
5204/// the method declaration. For example, we could see an
5205/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00005206void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005207 if (!ParamD)
5208 return;
Mike Stump11289f42009-09-09 15:08:12 +00005209
John McCall48871652010-08-21 09:40:31 +00005210 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00005211
5212 // If this parameter has an unparsed default argument, clear it out
5213 // to make way for the parsed default argument.
5214 if (Param->hasUnparsedDefaultArg())
5215 Param->setDefaultArg(0);
5216
John McCall48871652010-08-21 09:40:31 +00005217 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005218 if (Param->getDeclName())
5219 IdResolver.AddDecl(Param);
5220}
5221
5222/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5223/// processing the delayed method declaration for Method. The method
5224/// declaration is now considered finished. There may be a separate
5225/// ActOnStartOfFunctionDef action later (not necessarily
5226/// immediately!) for this method, if it was also defined inside the
5227/// class body.
John McCall48871652010-08-21 09:40:31 +00005228void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005229 if (!MethodD)
5230 return;
Mike Stump11289f42009-09-09 15:08:12 +00005231
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005232 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005233
John McCall48871652010-08-21 09:40:31 +00005234 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005235
5236 // Now that we have our default arguments, check the constructor
5237 // again. It could produce additional diagnostics or affect whether
5238 // the class has implicitly-declared destructors, among other
5239 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005240 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5241 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005242
5243 // Check the default arguments, which we may have added.
5244 if (!Method->isInvalidDecl())
5245 CheckCXXDefaultArguments(Method);
5246}
5247
Douglas Gregor831c93f2008-11-05 20:51:48 +00005248/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005249/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005250/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005251/// emit diagnostics and set the invalid bit to true. In any case, the type
5252/// will be updated to reflect a well-formed type for the constructor and
5253/// returned.
5254QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005255 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005256 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005257
5258 // C++ [class.ctor]p3:
5259 // A constructor shall not be virtual (10.3) or static (9.4). A
5260 // constructor can be invoked for a const, volatile or const
5261 // volatile object. A constructor shall not be declared const,
5262 // volatile, or const volatile (9.3.2).
5263 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005264 if (!D.isInvalidType())
5265 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5266 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5267 << SourceRange(D.getIdentifierLoc());
5268 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005269 }
John McCall8e7d6562010-08-26 03:08:43 +00005270 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005271 if (!D.isInvalidType())
5272 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5273 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5274 << SourceRange(D.getIdentifierLoc());
5275 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005276 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005277 }
Mike Stump11289f42009-09-09 15:08:12 +00005278
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005279 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005280 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005281 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005282 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5283 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005284 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005285 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5286 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005287 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005288 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5289 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005290 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
Douglas Gregordb9d6642011-01-26 05:01:58 +00005293 // C++0x [class.ctor]p4:
5294 // A constructor shall not be declared with a ref-qualifier.
5295 if (FTI.hasRefQualifier()) {
5296 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5297 << FTI.RefQualifierIsLValueRef
5298 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5299 D.setInvalidType();
5300 }
5301
Douglas Gregor831c93f2008-11-05 20:51:48 +00005302 // Rebuild the function type "R" without any type qualifiers (in
5303 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005304 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005305 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005306 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5307 return R;
5308
5309 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5310 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005311 EPI.RefQualifier = RQ_None;
5312
Chris Lattner38378bf2009-04-25 08:28:21 +00005313 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005314 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005315}
5316
Douglas Gregor4d87df52008-12-16 21:30:33 +00005317/// CheckConstructor - Checks a fully-formed constructor for
5318/// well-formedness, issuing any diagnostics required. Returns true if
5319/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005320void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005321 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005322 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5323 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005324 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005325
5326 // C++ [class.copy]p3:
5327 // A declaration of a constructor for a class X is ill-formed if
5328 // its first parameter is of type (optionally cv-qualified) X and
5329 // either there are no other parameters or else all other
5330 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005331 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005332 ((Constructor->getNumParams() == 1) ||
5333 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005334 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5335 Constructor->getTemplateSpecializationKind()
5336 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005337 QualType ParamType = Constructor->getParamDecl(0)->getType();
5338 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5339 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005340 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005341 const char *ConstRef
5342 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5343 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005344 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005345 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005346
5347 // FIXME: Rather that making the constructor invalid, we should endeavor
5348 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005349 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005350 }
5351 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005352}
5353
John McCalldeb646e2010-08-04 01:04:25 +00005354/// CheckDestructor - Checks a fully-formed destructor definition for
5355/// well-formedness, issuing any diagnostics required. Returns true
5356/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005357bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005358 CXXRecordDecl *RD = Destructor->getParent();
5359
5360 if (Destructor->isVirtual()) {
5361 SourceLocation Loc;
5362
5363 if (!Destructor->isImplicit())
5364 Loc = Destructor->getLocation();
5365 else
5366 Loc = RD->getLocation();
5367
5368 // If we have a virtual destructor, look up the deallocation function
5369 FunctionDecl *OperatorDelete = 0;
5370 DeclarationName Name =
5371 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005372 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005373 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005374
5375 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005376
5377 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005378 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005379
5380 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005381}
5382
Mike Stump11289f42009-09-09 15:08:12 +00005383static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005384FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5385 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5386 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005387 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005388}
5389
Douglas Gregor831c93f2008-11-05 20:51:48 +00005390/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5391/// the well-formednes of the destructor declarator @p D with type @p
5392/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005393/// emit diagnostics and set the declarator to invalid. Even if this happens,
5394/// will be updated to reflect a well-formed type for the destructor and
5395/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005396QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005397 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005398 // C++ [class.dtor]p1:
5399 // [...] A typedef-name that names a class is a class-name
5400 // (7.1.3); however, a typedef-name that names a class shall not
5401 // be used as the identifier in the declarator for a destructor
5402 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005403 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005404 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005405 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005406 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005407 else if (const TemplateSpecializationType *TST =
5408 DeclaratorType->getAs<TemplateSpecializationType>())
5409 if (TST->isTypeAlias())
5410 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5411 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005412
5413 // C++ [class.dtor]p2:
5414 // A destructor is used to destroy objects of its class type. A
5415 // destructor takes no parameters, and no return type can be
5416 // specified for it (not even void). The address of a destructor
5417 // shall not be taken. A destructor shall not be static. A
5418 // destructor can be invoked for a const, volatile or const
5419 // volatile object. A destructor shall not be declared const,
5420 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005421 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005422 if (!D.isInvalidType())
5423 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5424 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005425 << SourceRange(D.getIdentifierLoc())
5426 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5427
John McCall8e7d6562010-08-26 03:08:43 +00005428 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005429 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005430 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005431 // Destructors don't have return types, but the parser will
5432 // happily parse something like:
5433 //
5434 // class X {
5435 // float ~X();
5436 // };
5437 //
5438 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005439 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5440 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5441 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005442 }
Mike Stump11289f42009-09-09 15:08:12 +00005443
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005444 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005445 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005446 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005447 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5448 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005449 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005450 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5451 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005452 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005453 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5454 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005455 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005456 }
5457
Douglas Gregordb9d6642011-01-26 05:01:58 +00005458 // C++0x [class.dtor]p2:
5459 // A destructor shall not be declared with a ref-qualifier.
5460 if (FTI.hasRefQualifier()) {
5461 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5462 << FTI.RefQualifierIsLValueRef
5463 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5464 D.setInvalidType();
5465 }
5466
Douglas Gregor831c93f2008-11-05 20:51:48 +00005467 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005468 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005469 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5470
5471 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005472 FTI.freeArgs();
5473 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005474 }
5475
Mike Stump11289f42009-09-09 15:08:12 +00005476 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005477 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005478 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005479 D.setInvalidType();
5480 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005481
5482 // Rebuild the function type "R" without any type qualifiers or
5483 // parameters (in case any of the errors above fired) and with
5484 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005485 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005486 if (!D.isInvalidType())
5487 return R;
5488
Douglas Gregor95755162010-07-01 05:10:53 +00005489 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005490 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5491 EPI.Variadic = false;
5492 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005493 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005494 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005495}
5496
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005497/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5498/// well-formednes of the conversion function declarator @p D with
5499/// type @p R. If there are any errors in the declarator, this routine
5500/// will emit diagnostics and return true. Otherwise, it will return
5501/// false. Either way, the type @p R will be updated to reflect a
5502/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005503void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005504 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005505 // C++ [class.conv.fct]p1:
5506 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005507 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005508 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005509 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005510 if (!D.isInvalidType())
5511 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5512 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5513 << SourceRange(D.getIdentifierLoc());
5514 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005515 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005516 }
John McCall212fa2e2010-04-13 00:04:31 +00005517
5518 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5519
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005520 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005521 // Conversion functions don't have return types, but the parser will
5522 // happily parse something like:
5523 //
5524 // class X {
5525 // float operator bool();
5526 // };
5527 //
5528 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005529 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5530 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5531 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005532 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005533 }
5534
John McCall212fa2e2010-04-13 00:04:31 +00005535 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5536
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005537 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005538 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005539 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5540
5541 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005542 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005543 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005544 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005545 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005546 D.setInvalidType();
5547 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005548
John McCall212fa2e2010-04-13 00:04:31 +00005549 // Diagnose "&operator bool()" and other such nonsense. This
5550 // is actually a gcc extension which we don't support.
5551 if (Proto->getResultType() != ConvType) {
5552 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5553 << Proto->getResultType();
5554 D.setInvalidType();
5555 ConvType = Proto->getResultType();
5556 }
5557
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005558 // C++ [class.conv.fct]p4:
5559 // The conversion-type-id shall not represent a function type nor
5560 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005561 if (ConvType->isArrayType()) {
5562 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5563 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005564 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005565 } else if (ConvType->isFunctionType()) {
5566 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5567 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005568 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005569 }
5570
5571 // Rebuild the function type "R" without any parameters (in case any
5572 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005573 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005574 if (D.isInvalidType())
5575 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005576
Douglas Gregor5fb53972009-01-14 15:45:31 +00005577 // C++0x explicit conversion operators.
5578 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00005579 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00005580 diag::warn_explicit_conversion_functions)
5581 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005582}
5583
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005584/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5585/// the declaration of the given C++ conversion function. This routine
5586/// is responsible for recording the conversion function in the C++
5587/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005588Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005589 assert(Conversion && "Expected to receive a conversion function declaration");
5590
Douglas Gregor4287b372008-12-12 08:25:50 +00005591 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005592
5593 // Make sure we aren't redeclaring the conversion function.
5594 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005595
5596 // C++ [class.conv.fct]p1:
5597 // [...] A conversion function is never used to convert a
5598 // (possibly cv-qualified) object to the (possibly cv-qualified)
5599 // same object type (or a reference to it), to a (possibly
5600 // cv-qualified) base class of that type (or a reference to it),
5601 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005602 // FIXME: Suppress this warning if the conversion function ends up being a
5603 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005604 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005605 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005606 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005607 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005608 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5609 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005610 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005611 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005612 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5613 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005614 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005615 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005616 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005617 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005618 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005619 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005620 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005621 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005622 }
5623
Douglas Gregor457104e2010-09-29 04:25:11 +00005624 if (FunctionTemplateDecl *ConversionTemplate
5625 = Conversion->getDescribedFunctionTemplate())
5626 return ConversionTemplate;
5627
John McCall48871652010-08-21 09:40:31 +00005628 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005629}
5630
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005631//===----------------------------------------------------------------------===//
5632// Namespace Handling
5633//===----------------------------------------------------------------------===//
5634
John McCallb1be5232010-08-26 09:15:37 +00005635
5636
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005637/// ActOnStartNamespaceDef - This is called at the start of a namespace
5638/// definition.
John McCall48871652010-08-21 09:40:31 +00005639Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005640 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005641 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005642 SourceLocation IdentLoc,
5643 IdentifierInfo *II,
5644 SourceLocation LBrace,
5645 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005646 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5647 // For anonymous namespace, take the location of the left brace.
5648 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00005649 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005650 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005651 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005652
5653 Scope *DeclRegionScope = NamespcScope->getParent();
5654
Anders Carlssona7bcade2010-02-07 01:09:23 +00005655 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5656
John McCall2faf32c2010-12-10 02:59:44 +00005657 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5658 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00005659
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005660 if (II) {
5661 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005662 // The identifier in an original-namespace-definition shall not
5663 // have been previously defined in the declarative region in
5664 // which the original-namespace-definition appears. The
5665 // identifier in an original-namespace-definition is the name of
5666 // the namespace. Subsequently in that declarative region, it is
5667 // treated as an original-namespace-name.
5668 //
5669 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005670 // look through using directives, just look for any ordinary names.
5671
5672 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5673 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5674 Decl::IDNS_Namespace;
5675 NamedDecl *PrevDecl = 0;
5676 for (DeclContext::lookup_result R
5677 = CurContext->getRedeclContext()->lookup(II);
5678 R.first != R.second; ++R.first) {
5679 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5680 PrevDecl = *R.first;
5681 break;
5682 }
5683 }
5684
Douglas Gregor91f84212008-12-11 16:49:14 +00005685 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5686 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005687 if (Namespc->isInline() != OrigNS->isInline()) {
5688 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00005689 if (OrigNS->isInline()) {
5690 // The user probably just forgot the 'inline', so suggest that it
5691 // be added back.
5692 Diag(Namespc->getLocation(),
5693 diag::warn_inline_namespace_reopened_noninline)
5694 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5695 } else {
5696 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5697 << Namespc->isInline();
5698 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005699 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00005700
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005701 // Recover by ignoring the new namespace's inline status.
5702 Namespc->setInline(OrigNS->isInline());
5703 }
5704
Douglas Gregor91f84212008-12-11 16:49:14 +00005705 // Attach this namespace decl to the chain of extended namespace
5706 // definitions.
5707 OrigNS->setNextNamespace(Namespc);
5708 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005709
Mike Stump11289f42009-09-09 15:08:12 +00005710 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00005711 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00005712 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00005713 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005714 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005715 } else if (PrevDecl) {
5716 // This is an invalid name redefinition.
5717 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5718 << Namespc->getDeclName();
5719 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5720 Namespc->setInvalidDecl();
5721 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00005722 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005723 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005724 // This is the first "real" definition of the namespace "std", so update
5725 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005726 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005727 // We had already defined a dummy namespace "std". Link this new
5728 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005729 StdNS->setNextNamespace(Namespc);
5730 StdNS->setLocation(IdentLoc);
5731 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00005732 }
5733
5734 // Make our StdNamespace cache point at the first real definition of the
5735 // "std" namespace.
5736 StdNamespace = Namespc;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005737
5738 // Add this instance of "std" to the set of known namespaces
5739 KnownNamespaces[Namespc] = false;
5740 } else if (!Namespc->isInline()) {
5741 // Since this is an "original" namespace, add it to the known set of
5742 // namespaces if it is not an inline namespace.
5743 KnownNamespaces[Namespc] = false;
Mike Stump11289f42009-09-09 15:08:12 +00005744 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005745
5746 PushOnScopeChains(Namespc, DeclRegionScope);
5747 } else {
John McCall4fa53422009-10-01 00:25:31 +00005748 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00005749 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00005750
5751 // Link the anonymous namespace into its parent.
5752 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00005753 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005754 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5755 PrevDecl = TU->getAnonymousNamespace();
5756 TU->setAnonymousNamespace(Namespc);
5757 } else {
5758 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5759 PrevDecl = ND->getAnonymousNamespace();
5760 ND->setAnonymousNamespace(Namespc);
5761 }
5762
5763 // Link the anonymous namespace with its previous declaration.
5764 if (PrevDecl) {
5765 assert(PrevDecl->isAnonymousNamespace());
5766 assert(!PrevDecl->getNextNamespace());
5767 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5768 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005769
5770 if (Namespc->isInline() != PrevDecl->isInline()) {
5771 // inline-ness must match
5772 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5773 << Namespc->isInline();
5774 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5775 Namespc->setInvalidDecl();
5776 // Recover by ignoring the new namespace's inline status.
5777 Namespc->setInline(PrevDecl->isInline());
5778 }
John McCall0db42252009-12-16 02:06:49 +00005779 }
John McCall4fa53422009-10-01 00:25:31 +00005780
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005781 CurContext->addDecl(Namespc);
5782
John McCall4fa53422009-10-01 00:25:31 +00005783 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5784 // behaves as if it were replaced by
5785 // namespace unique { /* empty body */ }
5786 // using namespace unique;
5787 // namespace unique { namespace-body }
5788 // where all occurrences of 'unique' in a translation unit are
5789 // replaced by the same identifier and this identifier differs
5790 // from all other identifiers in the entire program.
5791
5792 // We just create the namespace with an empty name and then add an
5793 // implicit using declaration, just like the standard suggests.
5794 //
5795 // CodeGen enforces the "universally unique" aspect by giving all
5796 // declarations semantically contained within an anonymous
5797 // namespace internal linkage.
5798
John McCall0db42252009-12-16 02:06:49 +00005799 if (!PrevDecl) {
5800 UsingDirectiveDecl* UD
5801 = UsingDirectiveDecl::Create(Context, CurContext,
5802 /* 'using' */ LBrace,
5803 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005804 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005805 /* identifier */ SourceLocation(),
5806 Namespc,
5807 /* Ancestor */ CurContext);
5808 UD->setImplicit();
5809 CurContext->addDecl(UD);
5810 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005811 }
5812
5813 // Although we could have an invalid decl (i.e. the namespace name is a
5814 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005815 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5816 // for the namespace has the declarations that showed up in that particular
5817 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005818 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005819 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005820}
5821
Sebastian Redla6602e92009-11-23 15:34:23 +00005822/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5823/// is a namespace alias, returns the namespace it points to.
5824static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5825 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5826 return AD->getNamespace();
5827 return dyn_cast_or_null<NamespaceDecl>(D);
5828}
5829
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005830/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5831/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005832void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005833 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5834 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005835 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005836 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005837 if (Namespc->hasAttr<VisibilityAttr>())
5838 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005839}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005840
John McCall28a0cf72010-08-25 07:42:41 +00005841CXXRecordDecl *Sema::getStdBadAlloc() const {
5842 return cast_or_null<CXXRecordDecl>(
5843 StdBadAlloc.get(Context.getExternalSource()));
5844}
5845
5846NamespaceDecl *Sema::getStdNamespace() const {
5847 return cast_or_null<NamespaceDecl>(
5848 StdNamespace.get(Context.getExternalSource()));
5849}
5850
Douglas Gregorcdf87022010-06-29 17:53:46 +00005851/// \brief Retrieve the special "std" namespace, which may require us to
5852/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005853NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005854 if (!StdNamespace) {
5855 // The "std" namespace has not yet been defined, so build one implicitly.
5856 StdNamespace = NamespaceDecl::Create(Context,
5857 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005858 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00005859 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005860 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005861 }
5862
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005863 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005864}
5865
Douglas Gregora172e082011-03-26 22:25:30 +00005866/// \brief Determine whether a using statement is in a context where it will be
5867/// apply in all contexts.
5868static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5869 switch (CurContext->getDeclKind()) {
5870 case Decl::TranslationUnit:
5871 return true;
5872 case Decl::LinkageSpec:
5873 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5874 default:
5875 return false;
5876 }
5877}
5878
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005879static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5880 CXXScopeSpec &SS,
5881 SourceLocation IdentLoc,
5882 IdentifierInfo *Ident) {
5883 R.clear();
5884 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5885 R.getLookupKind(), Sc, &SS, NULL,
5886 false, S.CTC_NoKeywords, NULL)) {
5887 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5888 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5889 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5890 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5891 if (DeclContext *DC = S.computeDeclContext(SS, false))
5892 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5893 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5894 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5895 else
5896 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5897 << Ident << CorrectedQuotedStr
5898 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5899
5900 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5901 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5902
5903 Ident = Corrected.getCorrectionAsIdentifierInfo();
5904 R.addDecl(Corrected.getCorrectionDecl());
5905 return true;
5906 }
5907 R.setLookupName(Ident);
5908 }
5909 return false;
5910}
5911
John McCall48871652010-08-21 09:40:31 +00005912Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005913 SourceLocation UsingLoc,
5914 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005915 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005916 SourceLocation IdentLoc,
5917 IdentifierInfo *NamespcName,
5918 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00005919 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5920 assert(NamespcName && "Invalid NamespcName.");
5921 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00005922
5923 // This can only happen along a recovery path.
5924 while (S->getFlags() & Scope::TemplateParamScope)
5925 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00005926 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00005927
Douglas Gregor889ceb72009-02-03 19:21:40 +00005928 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00005929 NestedNameSpecifier *Qualifier = 0;
5930 if (SS.isSet())
5931 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5932
Douglas Gregor34074322009-01-14 22:20:51 +00005933 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005934 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5935 LookupParsedName(R, S, &SS);
5936 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005937 return 0;
John McCall27b18f82009-11-17 02:14:36 +00005938
Douglas Gregorcdf87022010-06-29 17:53:46 +00005939 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005940 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005941 // Allow "using namespace std;" or "using namespace ::std;" even if
5942 // "std" hasn't been defined yet, for GCC compatibility.
5943 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5944 NamespcName->isStr("std")) {
5945 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005946 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00005947 R.resolveKind();
5948 }
5949 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005950 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005951 }
5952
John McCall9f3059a2009-10-09 21:13:30 +00005953 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00005954 NamedDecl *Named = R.getFoundDecl();
5955 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5956 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00005957 // C++ [namespace.udir]p1:
5958 // A using-directive specifies that the names in the nominated
5959 // namespace can be used in the scope in which the
5960 // using-directive appears after the using-directive. During
5961 // unqualified name lookup (3.4.1), the names appear as if they
5962 // were declared in the nearest enclosing namespace which
5963 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00005964 // namespace. [Note: in this context, "contains" means "contains
5965 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00005966
5967 // Find enclosing context containing both using-directive and
5968 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00005969 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005970 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5971 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5972 CommonAncestor = CommonAncestor->getParent();
5973
Sebastian Redla6602e92009-11-23 15:34:23 +00005974 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00005975 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00005976 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005977
Douglas Gregora172e082011-03-26 22:25:30 +00005978 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00005979 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005980 Diag(IdentLoc, diag::warn_using_directive_in_header);
5981 }
5982
Douglas Gregor889ceb72009-02-03 19:21:40 +00005983 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005984 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00005985 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00005986 }
5987
Douglas Gregor889ceb72009-02-03 19:21:40 +00005988 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00005989 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00005990}
5991
5992void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5993 // If scope has associated entity, then using directive is at namespace
5994 // or translation unit scope. We add UsingDirectiveDecls, into
5995 // it's lookup structure.
5996 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005997 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005998 else
5999 // Otherwise it is block-sope. using-directives will affect lookup
6000 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00006001 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006002}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006003
Douglas Gregorfec52632009-06-20 00:51:54 +00006004
John McCall48871652010-08-21 09:40:31 +00006005Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006006 AccessSpecifier AS,
6007 bool HasUsingKeyword,
6008 SourceLocation UsingLoc,
6009 CXXScopeSpec &SS,
6010 UnqualifiedId &Name,
6011 AttributeList *AttrList,
6012 bool IsTypeName,
6013 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006014 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006015
Douglas Gregor220f4272009-11-04 16:30:06 +00006016 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006017 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006018 case UnqualifiedId::IK_Identifier:
6019 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006020 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006021 case UnqualifiedId::IK_ConversionFunctionId:
6022 break;
6023
6024 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00006025 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00006026 // C++0x inherited constructors.
6027 if (getLangOptions().CPlusPlus0x) break;
6028
Douglas Gregor220f4272009-11-04 16:30:06 +00006029 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
6030 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006031 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006032
6033 case UnqualifiedId::IK_DestructorName:
6034 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6035 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006036 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006037
6038 case UnqualifiedId::IK_TemplateId:
6039 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6040 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006041 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006042 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006043
6044 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6045 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006046 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00006047 return 0;
John McCall3969e302009-12-08 07:46:18 +00006048
John McCalla0097262009-12-11 02:10:03 +00006049 // Warn about using declarations.
6050 // TODO: store that the declaration was written without 'using' and
6051 // talk about access decls instead of using decls in the
6052 // diagnostics.
6053 if (!HasUsingKeyword) {
6054 UsingLoc = Name.getSourceRange().getBegin();
6055
6056 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00006057 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00006058 }
6059
Douglas Gregorc4356532010-12-16 00:46:58 +00006060 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6061 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6062 return 0;
6063
John McCall3f746822009-11-17 05:59:44 +00006064 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006065 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006066 /* IsInstantiation */ false,
6067 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00006068 if (UD)
6069 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00006070
John McCall48871652010-08-21 09:40:31 +00006071 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00006072}
6073
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006074/// \brief Determine whether a using declaration considers the given
6075/// declarations as "equivalent", e.g., if they are redeclarations of
6076/// the same entity or are both typedefs of the same type.
6077static bool
6078IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6079 bool &SuppressRedeclaration) {
6080 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6081 SuppressRedeclaration = false;
6082 return true;
6083 }
6084
Richard Smithdda56e42011-04-15 14:24:37 +00006085 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6086 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006087 SuppressRedeclaration = true;
6088 return Context.hasSameType(TD1->getUnderlyingType(),
6089 TD2->getUnderlyingType());
6090 }
6091
6092 return false;
6093}
6094
6095
John McCall84d87672009-12-10 09:41:52 +00006096/// Determines whether to create a using shadow decl for a particular
6097/// decl, given the set of decls existing prior to this using lookup.
6098bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6099 const LookupResult &Previous) {
6100 // Diagnose finding a decl which is not from a base class of the
6101 // current class. We do this now because there are cases where this
6102 // function will silently decide not to build a shadow decl, which
6103 // will pre-empt further diagnostics.
6104 //
6105 // We don't need to do this in C++0x because we do the check once on
6106 // the qualifier.
6107 //
6108 // FIXME: diagnose the following if we care enough:
6109 // struct A { int foo; };
6110 // struct B : A { using A::foo; };
6111 // template <class T> struct C : A {};
6112 // template <class T> struct D : C<T> { using B::foo; } // <---
6113 // This is invalid (during instantiation) in C++03 because B::foo
6114 // resolves to the using decl in B, which is not a base class of D<T>.
6115 // We can't diagnose it immediately because C<T> is an unknown
6116 // specialization. The UsingShadowDecl in D<T> then points directly
6117 // to A::foo, which will look well-formed when we instantiate.
6118 // The right solution is to not collapse the shadow-decl chain.
6119 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6120 DeclContext *OrigDC = Orig->getDeclContext();
6121
6122 // Handle enums and anonymous structs.
6123 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6124 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6125 while (OrigRec->isAnonymousStructOrUnion())
6126 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6127
6128 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6129 if (OrigDC == CurContext) {
6130 Diag(Using->getLocation(),
6131 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006132 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006133 Diag(Orig->getLocation(), diag::note_using_decl_target);
6134 return true;
6135 }
6136
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006137 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00006138 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006139 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00006140 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006141 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006142 Diag(Orig->getLocation(), diag::note_using_decl_target);
6143 return true;
6144 }
6145 }
6146
6147 if (Previous.empty()) return false;
6148
6149 NamedDecl *Target = Orig;
6150 if (isa<UsingShadowDecl>(Target))
6151 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6152
John McCalla17e83e2009-12-11 02:33:26 +00006153 // If the target happens to be one of the previous declarations, we
6154 // don't have a conflict.
6155 //
6156 // FIXME: but we might be increasing its access, in which case we
6157 // should redeclare it.
6158 NamedDecl *NonTag = 0, *Tag = 0;
6159 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6160 I != E; ++I) {
6161 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006162 bool Result;
6163 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6164 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00006165
6166 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6167 }
6168
John McCall84d87672009-12-10 09:41:52 +00006169 if (Target->isFunctionOrFunctionTemplate()) {
6170 FunctionDecl *FD;
6171 if (isa<FunctionTemplateDecl>(Target))
6172 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6173 else
6174 FD = cast<FunctionDecl>(Target);
6175
6176 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00006177 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00006178 case Ovl_Overload:
6179 return false;
6180
6181 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00006182 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006183 break;
6184
6185 // We found a decl with the exact signature.
6186 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006187 // If we're in a record, we want to hide the target, so we
6188 // return true (without a diagnostic) to tell the caller not to
6189 // build a shadow decl.
6190 if (CurContext->isRecord())
6191 return true;
6192
6193 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00006194 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006195 break;
6196 }
6197
6198 Diag(Target->getLocation(), diag::note_using_decl_target);
6199 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6200 return true;
6201 }
6202
6203 // Target is not a function.
6204
John McCall84d87672009-12-10 09:41:52 +00006205 if (isa<TagDecl>(Target)) {
6206 // No conflict between a tag and a non-tag.
6207 if (!Tag) return false;
6208
John McCalle29c5cd2009-12-10 19:51:03 +00006209 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006210 Diag(Target->getLocation(), diag::note_using_decl_target);
6211 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6212 return true;
6213 }
6214
6215 // No conflict between a tag and a non-tag.
6216 if (!NonTag) return false;
6217
John McCalle29c5cd2009-12-10 19:51:03 +00006218 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006219 Diag(Target->getLocation(), diag::note_using_decl_target);
6220 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6221 return true;
6222}
6223
John McCall3f746822009-11-17 05:59:44 +00006224/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00006225UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00006226 UsingDecl *UD,
6227 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00006228
6229 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00006230 NamedDecl *Target = Orig;
6231 if (isa<UsingShadowDecl>(Target)) {
6232 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6233 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006234 }
6235
6236 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006237 = UsingShadowDecl::Create(Context, CurContext,
6238 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006239 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006240
6241 Shadow->setAccess(UD->getAccess());
6242 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6243 Shadow->setInvalidDecl();
6244
John McCall3f746822009-11-17 05:59:44 +00006245 if (S)
John McCall3969e302009-12-08 07:46:18 +00006246 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006247 else
John McCall3969e302009-12-08 07:46:18 +00006248 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006249
John McCall3969e302009-12-08 07:46:18 +00006250
John McCall84d87672009-12-10 09:41:52 +00006251 return Shadow;
6252}
John McCall3969e302009-12-08 07:46:18 +00006253
John McCall84d87672009-12-10 09:41:52 +00006254/// Hides a using shadow declaration. This is required by the current
6255/// using-decl implementation when a resolvable using declaration in a
6256/// class is followed by a declaration which would hide or override
6257/// one or more of the using decl's targets; for example:
6258///
6259/// struct Base { void foo(int); };
6260/// struct Derived : Base {
6261/// using Base::foo;
6262/// void foo(int);
6263/// };
6264///
6265/// The governing language is C++03 [namespace.udecl]p12:
6266///
6267/// When a using-declaration brings names from a base class into a
6268/// derived class scope, member functions in the derived class
6269/// override and/or hide member functions with the same name and
6270/// parameter types in a base class (rather than conflicting).
6271///
6272/// There are two ways to implement this:
6273/// (1) optimistically create shadow decls when they're not hidden
6274/// by existing declarations, or
6275/// (2) don't create any shadow decls (or at least don't make them
6276/// visible) until we've fully parsed/instantiated the class.
6277/// The problem with (1) is that we might have to retroactively remove
6278/// a shadow decl, which requires several O(n) operations because the
6279/// decl structures are (very reasonably) not designed for removal.
6280/// (2) avoids this but is very fiddly and phase-dependent.
6281void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006282 if (Shadow->getDeclName().getNameKind() ==
6283 DeclarationName::CXXConversionFunctionName)
6284 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6285
John McCall84d87672009-12-10 09:41:52 +00006286 // Remove it from the DeclContext...
6287 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006288
John McCall84d87672009-12-10 09:41:52 +00006289 // ...and the scope, if applicable...
6290 if (S) {
John McCall48871652010-08-21 09:40:31 +00006291 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00006292 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006293 }
6294
John McCall84d87672009-12-10 09:41:52 +00006295 // ...and the using decl.
6296 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6297
6298 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00006299 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00006300}
6301
John McCalle61f2ba2009-11-18 02:36:19 +00006302/// Builds a using declaration.
6303///
6304/// \param IsInstantiation - Whether this call arises from an
6305/// instantiation of an unresolved using declaration. We treat
6306/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00006307NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6308 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006309 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006310 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00006311 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006312 bool IsInstantiation,
6313 bool IsTypeName,
6314 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00006315 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006316 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00006317 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00006318
Anders Carlssonf038fc22009-08-28 05:49:21 +00006319 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00006320
Anders Carlsson59140b32009-08-28 03:16:11 +00006321 if (SS.isEmpty()) {
6322 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00006323 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00006324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
John McCall84d87672009-12-10 09:41:52 +00006326 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006327 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00006328 ForRedeclaration);
6329 Previous.setHideTags(false);
6330 if (S) {
6331 LookupName(Previous, S);
6332
6333 // It is really dumb that we have to do this.
6334 LookupResult::Filter F = Previous.makeFilter();
6335 while (F.hasNext()) {
6336 NamedDecl *D = F.next();
6337 if (!isDeclInScope(D, CurContext, S))
6338 F.erase();
6339 }
6340 F.done();
6341 } else {
6342 assert(IsInstantiation && "no scope in non-instantiation");
6343 assert(CurContext->isRecord() && "scope not record in instantiation");
6344 LookupQualifiedName(Previous, CurContext);
6345 }
6346
John McCall84d87672009-12-10 09:41:52 +00006347 // Check for invalid redeclarations.
6348 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6349 return 0;
6350
6351 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00006352 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6353 return 0;
6354
John McCall84c16cf2009-11-12 03:15:40 +00006355 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006356 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006357 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00006358 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00006359 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00006360 // FIXME: not all declaration name kinds are legal here
6361 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6362 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006363 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006364 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00006365 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006366 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6367 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00006368 }
John McCallb96ec562009-12-04 22:46:56 +00006369 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006370 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6371 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00006372 }
John McCallb96ec562009-12-04 22:46:56 +00006373 D->setAccess(AS);
6374 CurContext->addDecl(D);
6375
6376 if (!LookupContext) return D;
6377 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00006378
John McCall0b66eb32010-05-01 00:40:08 +00006379 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00006380 UD->setInvalidDecl();
6381 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00006382 }
6383
Sebastian Redl08905022011-02-05 19:23:19 +00006384 // Constructor inheriting using decls get special treatment.
6385 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00006386 if (CheckInheritedConstructorUsingDecl(UD))
6387 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00006388 return UD;
6389 }
6390
6391 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00006392
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006393 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00006394
John McCall3969e302009-12-08 07:46:18 +00006395 // Unlike most lookups, we don't always want to hide tag
6396 // declarations: tag names are visible through the using declaration
6397 // even if hidden by ordinary names, *except* in a dependent context
6398 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00006399 if (!IsInstantiation)
6400 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00006401
John McCall27b18f82009-11-17 02:14:36 +00006402 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00006403
John McCall9f3059a2009-10-09 21:13:30 +00006404 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00006405 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006406 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006407 UD->setInvalidDecl();
6408 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006409 }
6410
John McCallb96ec562009-12-04 22:46:56 +00006411 if (R.isAmbiguous()) {
6412 UD->setInvalidDecl();
6413 return UD;
6414 }
Mike Stump11289f42009-09-09 15:08:12 +00006415
John McCalle61f2ba2009-11-18 02:36:19 +00006416 if (IsTypeName) {
6417 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00006418 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006419 Diag(IdentLoc, diag::err_using_typename_non_type);
6420 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6421 Diag((*I)->getUnderlyingDecl()->getLocation(),
6422 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006423 UD->setInvalidDecl();
6424 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006425 }
6426 } else {
6427 // If we asked for a non-typename and we got a type, error out,
6428 // but only if this is an instantiation of an unresolved using
6429 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00006430 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006431 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6432 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006433 UD->setInvalidDecl();
6434 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006435 }
Anders Carlsson59140b32009-08-28 03:16:11 +00006436 }
6437
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006438 // C++0x N2914 [namespace.udecl]p6:
6439 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00006440 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006441 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6442 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006443 UD->setInvalidDecl();
6444 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006445 }
Mike Stump11289f42009-09-09 15:08:12 +00006446
John McCall84d87672009-12-10 09:41:52 +00006447 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6448 if (!CheckUsingShadowDecl(UD, *I, Previous))
6449 BuildUsingShadowDecl(S, UD, *I);
6450 }
John McCall3f746822009-11-17 05:59:44 +00006451
6452 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006453}
6454
Sebastian Redl08905022011-02-05 19:23:19 +00006455/// Additional checks for a using declaration referring to a constructor name.
6456bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6457 if (UD->isTypeName()) {
6458 // FIXME: Cannot specify typename when specifying constructor
6459 return true;
6460 }
6461
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006462 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006463 assert(SourceType &&
6464 "Using decl naming constructor doesn't have type in scope spec.");
6465 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6466
6467 // Check whether the named type is a direct base class.
6468 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6469 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6470 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6471 BaseIt != BaseE; ++BaseIt) {
6472 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6473 if (CanonicalSourceType == BaseType)
6474 break;
6475 }
6476
6477 if (BaseIt == BaseE) {
6478 // Did not find SourceType in the bases.
6479 Diag(UD->getUsingLocation(),
6480 diag::err_using_decl_constructor_not_in_direct_base)
6481 << UD->getNameInfo().getSourceRange()
6482 << QualType(SourceType, 0) << TargetClass;
6483 return true;
6484 }
6485
6486 BaseIt->setInheritConstructors();
6487
6488 return false;
6489}
6490
John McCall84d87672009-12-10 09:41:52 +00006491/// Checks that the given using declaration is not an invalid
6492/// redeclaration. Note that this is checking only for the using decl
6493/// itself, not for any ill-formedness among the UsingShadowDecls.
6494bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6495 bool isTypeName,
6496 const CXXScopeSpec &SS,
6497 SourceLocation NameLoc,
6498 const LookupResult &Prev) {
6499 // C++03 [namespace.udecl]p8:
6500 // C++0x [namespace.udecl]p10:
6501 // A using-declaration is a declaration and can therefore be used
6502 // repeatedly where (and only where) multiple declarations are
6503 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006504 //
John McCall032092f2010-11-29 18:01:58 +00006505 // That's in non-member contexts.
6506 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006507 return false;
6508
6509 NestedNameSpecifier *Qual
6510 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6511
6512 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6513 NamedDecl *D = *I;
6514
6515 bool DTypename;
6516 NestedNameSpecifier *DQual;
6517 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6518 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006519 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006520 } else if (UnresolvedUsingValueDecl *UD
6521 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6522 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006523 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006524 } else if (UnresolvedUsingTypenameDecl *UD
6525 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6526 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006527 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006528 } else continue;
6529
6530 // using decls differ if one says 'typename' and the other doesn't.
6531 // FIXME: non-dependent using decls?
6532 if (isTypeName != DTypename) continue;
6533
6534 // using decls differ if they name different scopes (but note that
6535 // template instantiation can cause this check to trigger when it
6536 // didn't before instantiation).
6537 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6538 Context.getCanonicalNestedNameSpecifier(DQual))
6539 continue;
6540
6541 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006542 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006543 return true;
6544 }
6545
6546 return false;
6547}
6548
John McCall3969e302009-12-08 07:46:18 +00006549
John McCallb96ec562009-12-04 22:46:56 +00006550/// Checks that the given nested-name qualifier used in a using decl
6551/// in the current context is appropriately related to the current
6552/// scope. If an error is found, diagnoses it and returns true.
6553bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6554 const CXXScopeSpec &SS,
6555 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006556 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006557
John McCall3969e302009-12-08 07:46:18 +00006558 if (!CurContext->isRecord()) {
6559 // C++03 [namespace.udecl]p3:
6560 // C++0x [namespace.udecl]p8:
6561 // A using-declaration for a class member shall be a member-declaration.
6562
6563 // If we weren't able to compute a valid scope, it must be a
6564 // dependent class scope.
6565 if (!NamedContext || NamedContext->isRecord()) {
6566 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6567 << SS.getRange();
6568 return true;
6569 }
6570
6571 // Otherwise, everything is known to be fine.
6572 return false;
6573 }
6574
6575 // The current scope is a record.
6576
6577 // If the named context is dependent, we can't decide much.
6578 if (!NamedContext) {
6579 // FIXME: in C++0x, we can diagnose if we can prove that the
6580 // nested-name-specifier does not refer to a base class, which is
6581 // still possible in some cases.
6582
6583 // Otherwise we have to conservatively report that things might be
6584 // okay.
6585 return false;
6586 }
6587
6588 if (!NamedContext->isRecord()) {
6589 // Ideally this would point at the last name in the specifier,
6590 // but we don't have that level of source info.
6591 Diag(SS.getRange().getBegin(),
6592 diag::err_using_decl_nested_name_specifier_is_not_class)
6593 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6594 return true;
6595 }
6596
Douglas Gregor7c842292010-12-21 07:41:49 +00006597 if (!NamedContext->isDependentContext() &&
6598 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6599 return true;
6600
John McCall3969e302009-12-08 07:46:18 +00006601 if (getLangOptions().CPlusPlus0x) {
6602 // C++0x [namespace.udecl]p3:
6603 // In a using-declaration used as a member-declaration, the
6604 // nested-name-specifier shall name a base class of the class
6605 // being defined.
6606
6607 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6608 cast<CXXRecordDecl>(NamedContext))) {
6609 if (CurContext == NamedContext) {
6610 Diag(NameLoc,
6611 diag::err_using_decl_nested_name_specifier_is_current_class)
6612 << SS.getRange();
6613 return true;
6614 }
6615
6616 Diag(SS.getRange().getBegin(),
6617 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6618 << (NestedNameSpecifier*) SS.getScopeRep()
6619 << cast<CXXRecordDecl>(CurContext)
6620 << SS.getRange();
6621 return true;
6622 }
6623
6624 return false;
6625 }
6626
6627 // C++03 [namespace.udecl]p4:
6628 // A using-declaration used as a member-declaration shall refer
6629 // to a member of a base class of the class being defined [etc.].
6630
6631 // Salient point: SS doesn't have to name a base class as long as
6632 // lookup only finds members from base classes. Therefore we can
6633 // diagnose here only if we can prove that that can't happen,
6634 // i.e. if the class hierarchies provably don't intersect.
6635
6636 // TODO: it would be nice if "definitely valid" results were cached
6637 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6638 // need to be repeated.
6639
6640 struct UserData {
6641 llvm::DenseSet<const CXXRecordDecl*> Bases;
6642
6643 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6644 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6645 Data->Bases.insert(Base);
6646 return true;
6647 }
6648
6649 bool hasDependentBases(const CXXRecordDecl *Class) {
6650 return !Class->forallBases(collect, this);
6651 }
6652
6653 /// Returns true if the base is dependent or is one of the
6654 /// accumulated base classes.
6655 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6656 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6657 return !Data->Bases.count(Base);
6658 }
6659
6660 bool mightShareBases(const CXXRecordDecl *Class) {
6661 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6662 }
6663 };
6664
6665 UserData Data;
6666
6667 // Returns false if we find a dependent base.
6668 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6669 return false;
6670
6671 // Returns false if the class has a dependent base or if it or one
6672 // of its bases is present in the base set of the current context.
6673 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6674 return false;
6675
6676 Diag(SS.getRange().getBegin(),
6677 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6678 << (NestedNameSpecifier*) SS.getScopeRep()
6679 << cast<CXXRecordDecl>(CurContext)
6680 << SS.getRange();
6681
6682 return true;
John McCallb96ec562009-12-04 22:46:56 +00006683}
6684
Richard Smithdda56e42011-04-15 14:24:37 +00006685Decl *Sema::ActOnAliasDeclaration(Scope *S,
6686 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006687 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006688 SourceLocation UsingLoc,
6689 UnqualifiedId &Name,
6690 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006691 // Skip up to the relevant declaration scope.
6692 while (S->getFlags() & Scope::TemplateParamScope)
6693 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006694 assert((S->getFlags() & Scope::DeclScope) &&
6695 "got alias-declaration outside of declaration scope");
6696
6697 if (Type.isInvalid())
6698 return 0;
6699
6700 bool Invalid = false;
6701 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6702 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006703 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006704
6705 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6706 return 0;
6707
6708 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006709 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006710 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006711 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6712 TInfo->getTypeLoc().getBeginLoc());
6713 }
Richard Smithdda56e42011-04-15 14:24:37 +00006714
6715 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6716 LookupName(Previous, S);
6717
6718 // Warn about shadowing the name of a template parameter.
6719 if (Previous.isSingleResult() &&
6720 Previous.getFoundDecl()->isTemplateParameter()) {
6721 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6722 Previous.getFoundDecl()))
6723 Invalid = true;
6724 Previous.clear();
6725 }
6726
6727 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6728 "name in alias declaration must be an identifier");
6729 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6730 Name.StartLocation,
6731 Name.Identifier, TInfo);
6732
6733 NewTD->setAccess(AS);
6734
6735 if (Invalid)
6736 NewTD->setInvalidDecl();
6737
Richard Smith3f1b5d02011-05-05 21:57:07 +00006738 CheckTypedefForVariablyModifiedType(S, NewTD);
6739 Invalid |= NewTD->isInvalidDecl();
6740
Richard Smithdda56e42011-04-15 14:24:37 +00006741 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006742
6743 NamedDecl *NewND;
6744 if (TemplateParamLists.size()) {
6745 TypeAliasTemplateDecl *OldDecl = 0;
6746 TemplateParameterList *OldTemplateParams = 0;
6747
6748 if (TemplateParamLists.size() != 1) {
6749 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6750 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6751 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6752 }
6753 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6754
6755 // Only consider previous declarations in the same scope.
6756 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6757 /*ExplicitInstantiationOrSpecialization*/false);
6758 if (!Previous.empty()) {
6759 Redeclaration = true;
6760
6761 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6762 if (!OldDecl && !Invalid) {
6763 Diag(UsingLoc, diag::err_redefinition_different_kind)
6764 << Name.Identifier;
6765
6766 NamedDecl *OldD = Previous.getRepresentativeDecl();
6767 if (OldD->getLocation().isValid())
6768 Diag(OldD->getLocation(), diag::note_previous_definition);
6769
6770 Invalid = true;
6771 }
6772
6773 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6774 if (TemplateParameterListsAreEqual(TemplateParams,
6775 OldDecl->getTemplateParameters(),
6776 /*Complain=*/true,
6777 TPL_TemplateMatch))
6778 OldTemplateParams = OldDecl->getTemplateParameters();
6779 else
6780 Invalid = true;
6781
6782 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6783 if (!Invalid &&
6784 !Context.hasSameType(OldTD->getUnderlyingType(),
6785 NewTD->getUnderlyingType())) {
6786 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6787 // but we can't reasonably accept it.
6788 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6789 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6790 if (OldTD->getLocation().isValid())
6791 Diag(OldTD->getLocation(), diag::note_previous_definition);
6792 Invalid = true;
6793 }
6794 }
6795 }
6796
6797 // Merge any previous default template arguments into our parameters,
6798 // and check the parameter list.
6799 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6800 TPC_TypeAliasTemplate))
6801 return 0;
6802
6803 TypeAliasTemplateDecl *NewDecl =
6804 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6805 Name.Identifier, TemplateParams,
6806 NewTD);
6807
6808 NewDecl->setAccess(AS);
6809
6810 if (Invalid)
6811 NewDecl->setInvalidDecl();
6812 else if (OldDecl)
6813 NewDecl->setPreviousDeclaration(OldDecl);
6814
6815 NewND = NewDecl;
6816 } else {
6817 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6818 NewND = NewTD;
6819 }
Richard Smithdda56e42011-04-15 14:24:37 +00006820
6821 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006822 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006823
Richard Smith3f1b5d02011-05-05 21:57:07 +00006824 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006825}
6826
John McCall48871652010-08-21 09:40:31 +00006827Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006828 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006829 SourceLocation AliasLoc,
6830 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006831 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006832 SourceLocation IdentLoc,
6833 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006834
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006835 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006836 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6837 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006838
Anders Carlssondca83c42009-03-28 06:23:46 +00006839 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006840 NamedDecl *PrevDecl
6841 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6842 ForRedeclaration);
6843 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6844 PrevDecl = 0;
6845
6846 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006847 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006848 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006849 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006850 // FIXME: At some point, we'll want to create the (redundant)
6851 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006852 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006853 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006854 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006855 }
Mike Stump11289f42009-09-09 15:08:12 +00006856
Anders Carlssondca83c42009-03-28 06:23:46 +00006857 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6858 diag::err_redefinition_different_kind;
6859 Diag(AliasLoc, DiagID) << Alias;
6860 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006861 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006862 }
6863
John McCall27b18f82009-11-17 02:14:36 +00006864 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006865 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006866
John McCall9f3059a2009-10-09 21:13:30 +00006867 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006868 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006869 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006870 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006871 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006872 }
Mike Stump11289f42009-09-09 15:08:12 +00006873
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006874 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006875 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006876 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006877 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006878
John McCalld8d0d432010-02-16 06:53:13 +00006879 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006880 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006881}
6882
Douglas Gregora57478e2010-05-01 15:04:51 +00006883namespace {
6884 /// \brief Scoped object used to handle the state changes required in Sema
6885 /// to implicitly define the body of a C++ member function;
6886 class ImplicitlyDefinedFunctionScope {
6887 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006888 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006889
6890 public:
6891 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006892 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006893 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006894 S.PushFunctionScope();
6895 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6896 }
6897
6898 ~ImplicitlyDefinedFunctionScope() {
6899 S.PopExpressionEvaluationContext();
6900 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00006901 }
6902 };
6903}
6904
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006905Sema::ImplicitExceptionSpecification
6906Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006907 // C++ [except.spec]p14:
6908 // An implicitly declared special member function (Clause 12) shall have an
6909 // exception-specification. [...]
6910 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006911 if (ClassDecl->isInvalidDecl())
6912 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006913
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006914 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006915 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6916 BEnd = ClassDecl->bases_end();
6917 B != BEnd; ++B) {
6918 if (B->isVirtual()) // Handled below.
6919 continue;
6920
Douglas Gregor9672f922010-07-03 00:47:00 +00006921 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6922 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006923 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6924 // If this is a deleted function, add it anyway. This might be conformant
6925 // with the standard. This might not. I'm not sure. It might not matter.
6926 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006927 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006928 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006929 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006930
6931 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006932 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6933 BEnd = ClassDecl->vbases_end();
6934 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00006935 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6936 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006937 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6938 // If this is a deleted function, add it anyway. This might be conformant
6939 // with the standard. This might not. I'm not sure. It might not matter.
6940 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006941 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006942 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006943 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006944
6945 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006946 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6947 FEnd = ClassDecl->field_end();
6948 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00006949 if (F->hasInClassInitializer()) {
6950 if (Expr *E = F->getInClassInitializer())
6951 ExceptSpec.CalledExpr(E);
6952 else if (!F->isInvalidDecl())
6953 ExceptSpec.SetDelayed();
6954 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00006955 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00006956 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6957 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6958 // If this is a deleted function, add it anyway. This might be conformant
6959 // with the standard. This might not. I'm not sure. It might not matter.
6960 // In particular, the problem is that this function never gets called. It
6961 // might just be ill-formed because this function attempts to refer to
6962 // a deleted function here.
6963 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006964 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006965 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006966 }
John McCalldb40c7f2010-12-14 08:05:40 +00006967
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006968 return ExceptSpec;
6969}
6970
6971CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6972 CXXRecordDecl *ClassDecl) {
6973 // C++ [class.ctor]p5:
6974 // A default constructor for a class X is a constructor of class X
6975 // that can be called without an argument. If there is no
6976 // user-declared constructor for class X, a default constructor is
6977 // implicitly declared. An implicitly-declared default constructor
6978 // is an inline public member of its class.
6979 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6980 "Should not build implicit default constructor!");
6981
6982 ImplicitExceptionSpecification Spec =
6983 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6984 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00006985
Douglas Gregor6d880b12010-07-01 22:31:05 +00006986 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006987 CanQualType ClassType
6988 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006989 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006990 DeclarationName Name
6991 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006992 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006993 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00006994 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006995 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006996 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006997 /*TInfo=*/0,
6998 /*isExplicit=*/false,
6999 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007000 /*isImplicitlyDeclared=*/true,
7001 // FIXME: apply the rules for definitions here
7002 /*isConstexpr=*/false);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007003 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00007004 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007005 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00007006 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00007007
7008 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00007009 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7010
Douglas Gregor0be31a22010-07-02 17:43:08 +00007011 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00007012 PushOnScopeChains(DefaultCon, S, false);
7013 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007014
Alexis Huntd6da8762011-10-10 06:18:57 +00007015 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007016 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00007017
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007018 return DefaultCon;
7019}
7020
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007021void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7022 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00007023 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007024 !Constructor->doesThisDeclarationHaveABody() &&
7025 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007026 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007027
Anders Carlsson423f5d82010-04-23 16:04:08 +00007028 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00007029 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00007030
Douglas Gregora57478e2010-05-01 15:04:51 +00007031 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007032 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00007033 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007034 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007035 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007036 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00007037 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00007038 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00007039 }
Douglas Gregor73193272010-09-20 16:48:21 +00007040
7041 SourceLocation Loc = Constructor->getLocation();
7042 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7043
7044 Constructor->setUsed();
7045 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007046
7047 if (ASTMutationListener *L = getASTMutationListener()) {
7048 L->CompletedImplicitDefinition(Constructor);
7049 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007050}
7051
Richard Smith938f40b2011-06-11 17:19:42 +00007052/// Get any existing defaulted default constructor for the given class. Do not
7053/// implicitly define one if it does not exist.
7054static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7055 CXXRecordDecl *D) {
7056 ASTContext &Context = Self.Context;
7057 QualType ClassType = Context.getTypeDeclType(D);
7058 DeclarationName ConstructorName
7059 = Context.DeclarationNames.getCXXConstructorName(
7060 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7061
7062 DeclContext::lookup_const_iterator Con, ConEnd;
7063 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7064 Con != ConEnd; ++Con) {
7065 // A function template cannot be defaulted.
7066 if (isa<FunctionTemplateDecl>(*Con))
7067 continue;
7068
7069 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7070 if (Constructor->isDefaultConstructor())
7071 return Constructor->isDefaulted() ? Constructor : 0;
7072 }
7073 return 0;
7074}
7075
7076void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7077 if (!D) return;
7078 AdjustDeclIfTemplate(D);
7079
7080 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7081 CXXConstructorDecl *CtorDecl
7082 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7083
7084 if (!CtorDecl) return;
7085
7086 // Compute the exception specification for the default constructor.
7087 const FunctionProtoType *CtorTy =
7088 CtorDecl->getType()->castAs<FunctionProtoType>();
7089 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7090 ImplicitExceptionSpecification Spec =
7091 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7092 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7093 assert(EPI.ExceptionSpecType != EST_Delayed);
7094
7095 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7096 }
7097
7098 // If the default constructor is explicitly defaulted, checking the exception
7099 // specification is deferred until now.
7100 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7101 !ClassDecl->isDependentType())
7102 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7103}
7104
Sebastian Redl08905022011-02-05 19:23:19 +00007105void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7106 // We start with an initial pass over the base classes to collect those that
7107 // inherit constructors from. If there are none, we can forgo all further
7108 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007109 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00007110 BasesVector BasesToInheritFrom;
7111 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7112 BaseE = ClassDecl->bases_end();
7113 BaseIt != BaseE; ++BaseIt) {
7114 if (BaseIt->getInheritConstructors()) {
7115 QualType Base = BaseIt->getType();
7116 if (Base->isDependentType()) {
7117 // If we inherit constructors from anything that is dependent, just
7118 // abort processing altogether. We'll get another chance for the
7119 // instantiations.
7120 return;
7121 }
7122 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7123 }
7124 }
7125 if (BasesToInheritFrom.empty())
7126 return;
7127
7128 // Now collect the constructors that we already have in the current class.
7129 // Those take precedence over inherited constructors.
7130 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7131 // unless there is a user-declared constructor with the same signature in
7132 // the class where the using-declaration appears.
7133 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7134 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7135 CtorE = ClassDecl->ctor_end();
7136 CtorIt != CtorE; ++CtorIt) {
7137 ExistingConstructors.insert(
7138 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7139 }
7140
7141 Scope *S = getScopeForContext(ClassDecl);
7142 DeclarationName CreatedCtorName =
7143 Context.DeclarationNames.getCXXConstructorName(
7144 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7145
7146 // Now comes the true work.
7147 // First, we keep a map from constructor types to the base that introduced
7148 // them. Needed for finding conflicting constructors. We also keep the
7149 // actually inserted declarations in there, for pretty diagnostics.
7150 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7151 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7152 ConstructorToSourceMap InheritedConstructors;
7153 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7154 BaseE = BasesToInheritFrom.end();
7155 BaseIt != BaseE; ++BaseIt) {
7156 const RecordType *Base = *BaseIt;
7157 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7158 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7159 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7160 CtorE = BaseDecl->ctor_end();
7161 CtorIt != CtorE; ++CtorIt) {
7162 // Find the using declaration for inheriting this base's constructors.
7163 DeclarationName Name =
7164 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7165 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7166 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7167 SourceLocation UsingLoc = UD ? UD->getLocation() :
7168 ClassDecl->getLocation();
7169
7170 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7171 // from the class X named in the using-declaration consists of actual
7172 // constructors and notional constructors that result from the
7173 // transformation of defaulted parameters as follows:
7174 // - all non-template default constructors of X, and
7175 // - for each non-template constructor of X that has at least one
7176 // parameter with a default argument, the set of constructors that
7177 // results from omitting any ellipsis parameter specification and
7178 // successively omitting parameters with a default argument from the
7179 // end of the parameter-type-list.
7180 CXXConstructorDecl *BaseCtor = *CtorIt;
7181 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7182 const FunctionProtoType *BaseCtorType =
7183 BaseCtor->getType()->getAs<FunctionProtoType>();
7184
7185 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7186 maxParams = BaseCtor->getNumParams();
7187 params <= maxParams; ++params) {
7188 // Skip default constructors. They're never inherited.
7189 if (params == 0)
7190 continue;
7191 // Skip copy and move constructors for the same reason.
7192 if (CanBeCopyOrMove && params == 1)
7193 continue;
7194
7195 // Build up a function type for this particular constructor.
7196 // FIXME: The working paper does not consider that the exception spec
7197 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00007198 // source. This code doesn't yet, either. When it does, this code will
7199 // need to be delayed until after exception specifications and in-class
7200 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00007201 const Type *NewCtorType;
7202 if (params == maxParams)
7203 NewCtorType = BaseCtorType;
7204 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007205 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00007206 for (unsigned i = 0; i < params; ++i) {
7207 Args.push_back(BaseCtorType->getArgType(i));
7208 }
7209 FunctionProtoType::ExtProtoInfo ExtInfo =
7210 BaseCtorType->getExtProtoInfo();
7211 ExtInfo.Variadic = false;
7212 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7213 Args.data(), params, ExtInfo)
7214 .getTypePtr();
7215 }
7216 const Type *CanonicalNewCtorType =
7217 Context.getCanonicalType(NewCtorType);
7218
7219 // Now that we have the type, first check if the class already has a
7220 // constructor with this signature.
7221 if (ExistingConstructors.count(CanonicalNewCtorType))
7222 continue;
7223
7224 // Then we check if we have already declared an inherited constructor
7225 // with this signature.
7226 std::pair<ConstructorToSourceMap::iterator, bool> result =
7227 InheritedConstructors.insert(std::make_pair(
7228 CanonicalNewCtorType,
7229 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7230 if (!result.second) {
7231 // Already in the map. If it came from a different class, that's an
7232 // error. Not if it's from the same.
7233 CanQualType PreviousBase = result.first->second.first;
7234 if (CanonicalBase != PreviousBase) {
7235 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7236 const CXXConstructorDecl *PrevBaseCtor =
7237 PrevCtor->getInheritedConstructor();
7238 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7239
7240 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7241 Diag(BaseCtor->getLocation(),
7242 diag::note_using_decl_constructor_conflict_current_ctor);
7243 Diag(PrevBaseCtor->getLocation(),
7244 diag::note_using_decl_constructor_conflict_previous_ctor);
7245 Diag(PrevCtor->getLocation(),
7246 diag::note_using_decl_constructor_conflict_previous_using);
7247 }
7248 continue;
7249 }
7250
7251 // OK, we're there, now add the constructor.
7252 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00007253 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00007254 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7255 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00007256 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7257 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007258 /*ImplicitlyDeclared=*/true,
7259 // FIXME: Due to a defect in the standard, we treat inherited
7260 // constructors as constexpr even if that makes them ill-formed.
7261 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00007262 NewCtor->setAccess(BaseCtor->getAccess());
7263
7264 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007265 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00007266 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007267 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7268 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00007269 /*IdentifierInfo=*/0,
7270 BaseCtorType->getArgType(i),
7271 /*TInfo=*/0, SC_None,
7272 SC_None, /*DefaultArg=*/0));
7273 }
David Blaikie9c70e042011-09-21 18:16:56 +00007274 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00007275 NewCtor->setInheritedConstructor(BaseCtor);
7276
7277 PushOnScopeChains(NewCtor, S, false);
7278 ClassDecl->addDecl(NewCtor);
7279 result.first->second.second = NewCtor;
7280 }
7281 }
7282 }
7283}
7284
Alexis Huntf91729462011-05-12 22:46:25 +00007285Sema::ImplicitExceptionSpecification
7286Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00007287 // C++ [except.spec]p14:
7288 // An implicitly declared special member function (Clause 12) shall have
7289 // an exception-specification.
7290 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007291 if (ClassDecl->isInvalidDecl())
7292 return ExceptSpec;
7293
Douglas Gregorf1203042010-07-01 19:09:28 +00007294 // Direct base-class destructors.
7295 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7296 BEnd = ClassDecl->bases_end();
7297 B != BEnd; ++B) {
7298 if (B->isVirtual()) // Handled below.
7299 continue;
7300
7301 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7302 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007303 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007304 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007305
Douglas Gregorf1203042010-07-01 19:09:28 +00007306 // Virtual base-class destructors.
7307 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7308 BEnd = ClassDecl->vbases_end();
7309 B != BEnd; ++B) {
7310 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7311 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007312 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007313 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007314
Douglas Gregorf1203042010-07-01 19:09:28 +00007315 // Field destructors.
7316 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7317 FEnd = ClassDecl->field_end();
7318 F != FEnd; ++F) {
7319 if (const RecordType *RecordTy
7320 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7321 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007322 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007323 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007324
Alexis Huntf91729462011-05-12 22:46:25 +00007325 return ExceptSpec;
7326}
7327
7328CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7329 // C++ [class.dtor]p2:
7330 // If a class has no user-declared destructor, a destructor is
7331 // declared implicitly. An implicitly-declared destructor is an
7332 // inline public member of its class.
7333
7334 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00007335 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00007336 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7337
Douglas Gregor7454c562010-07-02 20:37:36 +00007338 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00007339 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007340
Douglas Gregorf1203042010-07-01 19:09:28 +00007341 CanQualType ClassType
7342 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007343 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00007344 DeclarationName Name
7345 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007346 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00007347 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007348 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7349 /*isInline=*/true,
7350 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00007351 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00007352 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00007353 Destructor->setImplicit();
7354 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00007355
7356 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00007357 ++ASTContext::NumImplicitDestructorsDeclared;
7358
7359 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007360 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00007361 PushOnScopeChains(Destructor, S, false);
7362 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00007363
7364 // This could be uniqued if it ever proves significant.
7365 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00007366
7367 if (ShouldDeleteDestructor(Destructor))
7368 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00007369
7370 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00007371
Douglas Gregorf1203042010-07-01 19:09:28 +00007372 return Destructor;
7373}
7374
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007375void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00007376 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007377 assert((Destructor->isDefaulted() &&
7378 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007379 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00007380 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007381 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007382
Douglas Gregor54818f02010-05-12 16:39:35 +00007383 if (Destructor->isInvalidDecl())
7384 return;
7385
Douglas Gregora57478e2010-05-01 15:04:51 +00007386 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007387
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007388 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00007389 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7390 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00007391
Douglas Gregor54818f02010-05-12 16:39:35 +00007392 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007393 Diag(CurrentLocation, diag::note_member_synthesized_at)
7394 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7395
7396 Destructor->setInvalidDecl();
7397 return;
7398 }
7399
Douglas Gregor73193272010-09-20 16:48:21 +00007400 SourceLocation Loc = Destructor->getLocation();
7401 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00007402 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007403 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007404 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007405
7406 if (ASTMutationListener *L = getASTMutationListener()) {
7407 L->CompletedImplicitDefinition(Destructor);
7408 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007409}
7410
Sebastian Redl623ea822011-05-19 05:13:44 +00007411void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7412 CXXDestructorDecl *destructor) {
7413 // C++11 [class.dtor]p3:
7414 // A declaration of a destructor that does not have an exception-
7415 // specification is implicitly considered to have the same exception-
7416 // specification as an implicit declaration.
7417 const FunctionProtoType *dtorType = destructor->getType()->
7418 getAs<FunctionProtoType>();
7419 if (dtorType->hasExceptionSpec())
7420 return;
7421
7422 ImplicitExceptionSpecification exceptSpec =
7423 ComputeDefaultedDtorExceptionSpec(classDecl);
7424
Chandler Carruth9a797572011-09-20 04:55:26 +00007425 // Replace the destructor's type, building off the existing one. Fortunately,
7426 // the only thing of interest in the destructor type is its extended info.
7427 // The return and arguments are fixed.
7428 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00007429 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7430 epi.NumExceptions = exceptSpec.size();
7431 epi.Exceptions = exceptSpec.data();
7432 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7433
7434 destructor->setType(ty);
7435
7436 // FIXME: If the destructor has a body that could throw, and the newly created
7437 // spec doesn't allow exceptions, we should emit a warning, because this
7438 // change in behavior can break conforming C++03 programs at runtime.
7439 // However, we don't have a body yet, so it needs to be done somewhere else.
7440}
7441
Sebastian Redl22653ba2011-08-30 19:58:05 +00007442/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00007443/// \c To.
7444///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007445/// This routine is used to copy/move the members of a class with an
7446/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00007447/// copied are arrays, this routine builds for loops to copy them.
7448///
7449/// \param S The Sema object used for type-checking.
7450///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007451/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007452///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007453/// \param T The type of the expressions being copied/moved. Both expressions
7454/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007455///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007456/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007457///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007458/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007459///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007460/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007461/// Otherwise, it's a non-static member subobject.
7462///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007463/// \param Copying Whether we're copying or moving.
7464///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007465/// \param Depth Internal parameter recording the depth of the recursion.
7466///
7467/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007468static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007469BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007470 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007471 bool CopyingBaseSubobject, bool Copying,
7472 unsigned Depth = 0) {
7473 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007474 // Each subobject is assigned in the manner appropriate to its type:
7475 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007476 // - if the subobject is of class type, as if by a call to operator= with
7477 // the subobject as the object expression and the corresponding
7478 // subobject of x as a single function argument (as if by explicit
7479 // qualification; that is, ignoring any possible virtual overriding
7480 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007481 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7482 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7483
7484 // Look for operator=.
7485 DeclarationName Name
7486 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7487 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7488 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7489
Sebastian Redl22653ba2011-08-30 19:58:05 +00007490 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007491 LookupResult::Filter F = OpLookup.makeFilter();
7492 while (F.hasNext()) {
7493 NamedDecl *D = F.next();
7494 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007495 if (Copying ? Method->isCopyAssignmentOperator() :
7496 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007497 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007498
Douglas Gregorb139cd52010-05-01 20:49:11 +00007499 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007500 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007501 F.done();
7502
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007503 // Suppress the protected check (C++ [class.protected]) for each of the
7504 // assignment operators we found. This strange dance is required when
7505 // we're assigning via a base classes's copy-assignment operator. To
7506 // ensure that we're getting the right base class subobject (without
7507 // ambiguities), we need to cast "this" to that subobject type; to
7508 // ensure that we don't go through the virtual call mechanism, we need
7509 // to qualify the operator= name with the base class (see below). However,
7510 // this means that if the base class has a protected copy assignment
7511 // operator, the protected member access check will fail. So, we
7512 // rewrite "protected" access to "public" access in this case, since we
7513 // know by construction that we're calling from a derived class.
7514 if (CopyingBaseSubobject) {
7515 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7516 L != LEnd; ++L) {
7517 if (L.getAccess() == AS_protected)
7518 L.setAccess(AS_public);
7519 }
7520 }
7521
Douglas Gregorb139cd52010-05-01 20:49:11 +00007522 // Create the nested-name-specifier that will be used to qualify the
7523 // reference to operator=; this is required to suppress the virtual
7524 // call mechanism.
7525 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00007526 SS.MakeTrivial(S.Context,
7527 NestedNameSpecifier::Create(S.Context, 0, false,
7528 T.getTypePtr()),
7529 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007530
7531 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007532 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007533 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007534 /*FirstQualifierInScope=*/0, OpLookup,
7535 /*TemplateArgs=*/0,
7536 /*SuppressQualifierCheck=*/true);
7537 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007538 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007539
7540 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007541
John McCalldadc5752010-08-24 06:29:42 +00007542 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007543 OpEqualRef.takeAs<Expr>(),
7544 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007545 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007546 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007547
7548 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007549 }
John McCallab8c2732010-03-16 06:11:48 +00007550
Douglas Gregorb139cd52010-05-01 20:49:11 +00007551 // - if the subobject is of scalar type, the built-in assignment
7552 // operator is used.
7553 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7554 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007555 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007556 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007557 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007558
7559 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007560 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007561
7562 // - if the subobject is an array, each element is assigned, in the
7563 // manner appropriate to the element type;
7564
7565 // Construct a loop over the array bounds, e.g.,
7566 //
7567 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7568 //
7569 // that will copy each of the array elements.
7570 QualType SizeType = S.Context.getSizeType();
7571
7572 // Create the iteration variable.
7573 IdentifierInfo *IterationVarName = 0;
7574 {
7575 llvm::SmallString<8> Str;
7576 llvm::raw_svector_ostream OS(Str);
7577 OS << "__i" << Depth;
7578 IterationVarName = &S.Context.Idents.get(OS.str());
7579 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007580 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007581 IterationVarName, SizeType,
7582 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007583 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007584
7585 // Initialize the iteration variable to zero.
7586 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007587 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007588
7589 // Create a reference to the iteration variable; we'll use this several
7590 // times throughout.
7591 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00007592 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007593 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7594
7595 // Create the DeclStmt that holds the iteration variable.
7596 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7597
7598 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007599 llvm::APInt Upper
7600 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007601 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00007602 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00007603 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7604 BO_NE, S.Context.BoolTy,
7605 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007606
7607 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007608 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007609 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7610 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007611
7612 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007613 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7614 IterationVarRef, Loc));
7615 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7616 IterationVarRef, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007617 if (!Copying) // Cast to rvalue
7618 From = CastForMoving(S, From);
7619
7620 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007621 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7622 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007623 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007624 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007625 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007626
7627 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007628 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007629 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007630 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007631 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007632}
7633
Alexis Hunt119f3652011-05-14 05:23:20 +00007634std::pair<Sema::ImplicitExceptionSpecification, bool>
7635Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7636 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007637 if (ClassDecl->isInvalidDecl())
7638 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7639
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007640 // C++ [class.copy]p10:
7641 // If the class definition does not explicitly declare a copy
7642 // assignment operator, one is declared implicitly.
7643 // The implicitly-defined copy assignment operator for a class X
7644 // will have the form
7645 //
7646 // X& X::operator=(const X&)
7647 //
7648 // if
7649 bool HasConstCopyAssignment = true;
7650
7651 // -- each direct base class B of X has a copy assignment operator
7652 // whose parameter is of type const B&, const volatile B& or B,
7653 // and
7654 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7655 BaseEnd = ClassDecl->bases_end();
7656 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007657 // We'll handle this below
7658 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7659 continue;
7660
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007661 assert(!Base->getType()->isDependentType() &&
7662 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007663 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7664 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7665 &HasConstCopyAssignment);
7666 }
7667
7668 // In C++0x, the above citation has "or virtual added"
7669 if (LangOpts.CPlusPlus0x) {
7670 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7671 BaseEnd = ClassDecl->vbases_end();
7672 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7673 assert(!Base->getType()->isDependentType() &&
7674 "Cannot generate implicit members for class with dependent bases.");
7675 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7676 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7677 &HasConstCopyAssignment);
7678 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007679 }
7680
7681 // -- for all the nonstatic data members of X that are of a class
7682 // type M (or array thereof), each such class type has a copy
7683 // assignment operator whose parameter is of type const M&,
7684 // const volatile M& or M.
7685 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7686 FieldEnd = ClassDecl->field_end();
7687 HasConstCopyAssignment && Field != FieldEnd;
7688 ++Field) {
7689 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007690 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7691 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7692 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007693 }
7694 }
7695
7696 // Otherwise, the implicitly declared copy assignment operator will
7697 // have the form
7698 //
7699 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007700
Douglas Gregor68e11362010-07-01 17:48:08 +00007701 // C++ [except.spec]p14:
7702 // An implicitly declared special member function (Clause 12) shall have an
7703 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007704
7705 // It is unspecified whether or not an implicit copy assignment operator
7706 // attempts to deduplicate calls to assignment operators of virtual bases are
7707 // made. As such, this exception specification is effectively unspecified.
7708 // Based on a similar decision made for constness in C++0x, we're erring on
7709 // the side of assuming such calls to be made regardless of whether they
7710 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007711 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007712 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7714 BaseEnd = ClassDecl->bases_end();
7715 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007716 if (Base->isVirtual())
7717 continue;
7718
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007719 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007720 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007721 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7722 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007723 ExceptSpec.CalledDecl(CopyAssign);
7724 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007725
7726 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7727 BaseEnd = ClassDecl->vbases_end();
7728 Base != BaseEnd; ++Base) {
7729 CXXRecordDecl *BaseClassDecl
7730 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7731 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7732 ArgQuals, false, 0))
7733 ExceptSpec.CalledDecl(CopyAssign);
7734 }
7735
Douglas Gregor68e11362010-07-01 17:48:08 +00007736 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7737 FieldEnd = ClassDecl->field_end();
7738 Field != FieldEnd;
7739 ++Field) {
7740 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007741 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7742 if (CXXMethodDecl *CopyAssign =
7743 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7744 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007745 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007746 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007747
Alexis Hunt119f3652011-05-14 05:23:20 +00007748 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7749}
7750
7751CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7752 // Note: The following rules are largely analoguous to the copy
7753 // constructor rules. Note that virtual bases are not taken into account
7754 // for determining the argument type of the operator. Note also that
7755 // operators taking an object instead of a reference are allowed.
7756
7757 ImplicitExceptionSpecification Spec(Context);
7758 bool Const;
7759 llvm::tie(Spec, Const) =
7760 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7761
7762 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7763 QualType RetType = Context.getLValueReferenceType(ArgType);
7764 if (Const)
7765 ArgType = ArgType.withConst();
7766 ArgType = Context.getLValueReferenceType(ArgType);
7767
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007768 // An implicitly-declared copy assignment operator is an inline public
7769 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007770 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007771 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007772 SourceLocation ClassLoc = ClassDecl->getLocation();
7773 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007774 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007775 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007776 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007777 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007778 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007779 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007780 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007781 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007782 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007783 CopyAssignment->setImplicit();
7784 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007785
7786 // Add the parameter to the operator.
7787 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007788 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007789 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007790 SC_None,
7791 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007792 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007793
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007794 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007795 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007796
Douglas Gregor0be31a22010-07-02 17:43:08 +00007797 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007798 PushOnScopeChains(CopyAssignment, S, false);
7799 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007800
Alexis Huntd74c85f2011-06-22 01:05:13 +00007801 // C++0x [class.copy]p18:
7802 // ... If the class definition declares a move constructor or move
7803 // assignment operator, the implicitly declared copy assignment operator is
7804 // defined as deleted; ...
7805 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7806 ClassDecl->hasUserDeclaredMoveAssignment() ||
7807 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007808 CopyAssignment->setDeletedAsWritten();
7809
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007810 AddOverriddenMethods(ClassDecl, CopyAssignment);
7811 return CopyAssignment;
7812}
7813
Douglas Gregorb139cd52010-05-01 20:49:11 +00007814void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7815 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007816 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007817 CopyAssignOperator->isOverloadedOperator() &&
7818 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007819 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007820 "DefineImplicitCopyAssignment called for wrong function");
7821
7822 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7823
7824 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7825 CopyAssignOperator->setInvalidDecl();
7826 return;
7827 }
7828
7829 CopyAssignOperator->setUsed();
7830
7831 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007832 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007833
7834 // C++0x [class.copy]p30:
7835 // The implicitly-defined or explicitly-defaulted copy assignment operator
7836 // for a non-union class X performs memberwise copy assignment of its
7837 // subobjects. The direct base classes of X are assigned first, in the
7838 // order of their declaration in the base-specifier-list, and then the
7839 // immediate non-static data members of X are assigned, in the order in
7840 // which they were declared in the class definition.
7841
7842 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007843 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007844
7845 // The parameter for the "other" object, which we are copying from.
7846 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7847 Qualifiers OtherQuals = Other->getType().getQualifiers();
7848 QualType OtherRefType = Other->getType();
7849 if (const LValueReferenceType *OtherRef
7850 = OtherRefType->getAs<LValueReferenceType>()) {
7851 OtherRefType = OtherRef->getPointeeType();
7852 OtherQuals = OtherRefType.getQualifiers();
7853 }
7854
7855 // Our location for everything implicitly-generated.
7856 SourceLocation Loc = CopyAssignOperator->getLocation();
7857
7858 // Construct a reference to the "other" object. We'll be using this
7859 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007860 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007861 assert(OtherRef && "Reference to parameter cannot fail!");
7862
7863 // Construct the "this" pointer. We'll be using this throughout the generated
7864 // ASTs.
7865 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7866 assert(This && "Reference to this cannot fail!");
7867
7868 // Assign base classes.
7869 bool Invalid = false;
7870 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7871 E = ClassDecl->bases_end(); Base != E; ++Base) {
7872 // Form the assignment:
7873 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7874 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007875 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007876 Invalid = true;
7877 continue;
7878 }
7879
John McCallcf142162010-08-07 06:22:56 +00007880 CXXCastPath BasePath;
7881 BasePath.push_back(Base);
7882
Douglas Gregorb139cd52010-05-01 20:49:11 +00007883 // Construct the "from" expression, which is an implicit cast to the
7884 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007885 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007886 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7887 CK_UncheckedDerivedToBase,
7888 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007889
7890 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007891 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007892
7893 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007894 To = ImpCastExprToType(To.take(),
7895 Context.getCVRQualifiedType(BaseType,
7896 CopyAssignOperator->getTypeQualifiers()),
7897 CK_UncheckedDerivedToBase,
7898 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007899
7900 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007901 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007902 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007903 /*CopyingBaseSubobject=*/true,
7904 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007905 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007906 Diag(CurrentLocation, diag::note_member_synthesized_at)
7907 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7908 CopyAssignOperator->setInvalidDecl();
7909 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007910 }
7911
7912 // Success! Record the copy.
7913 Statements.push_back(Copy.takeAs<Expr>());
7914 }
7915
7916 // \brief Reference to the __builtin_memcpy function.
7917 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007918 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007919 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007920
7921 // Assign non-static members.
7922 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7923 FieldEnd = ClassDecl->field_end();
7924 Field != FieldEnd; ++Field) {
7925 // Check for members of reference type; we can't copy those.
7926 if (Field->getType()->isReferenceType()) {
7927 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7928 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7929 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007930 Diag(CurrentLocation, diag::note_member_synthesized_at)
7931 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007932 Invalid = true;
7933 continue;
7934 }
7935
7936 // Check for members of const-qualified, non-class type.
7937 QualType BaseType = Context.getBaseElementType(Field->getType());
7938 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7939 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7940 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7941 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007942 Diag(CurrentLocation, diag::note_member_synthesized_at)
7943 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007944 Invalid = true;
7945 continue;
7946 }
John McCall1b1a1db2011-06-17 00:18:42 +00007947
7948 // Suppress assigning zero-width bitfields.
7949 if (const Expr *Width = Field->getBitWidth())
7950 if (Width->EvaluateAsInt(Context) == 0)
7951 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007952
7953 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007954 if (FieldType->isIncompleteArrayType()) {
7955 assert(ClassDecl->hasFlexibleArrayMember() &&
7956 "Incomplete array type is not valid");
7957 continue;
7958 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007959
7960 // Build references to the field in the object we're copying from and to.
7961 CXXScopeSpec SS; // Intentionally empty
7962 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7963 LookupMemberName);
7964 MemberLookup.addDecl(*Field);
7965 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00007966 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00007967 Loc, /*IsArrow=*/false,
7968 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00007969 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00007970 Loc, /*IsArrow=*/true,
7971 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007972 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7973 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7974
7975 // If the field should be copied with __builtin_memcpy rather than via
7976 // explicit assignments, do so. This optimization only applies for arrays
7977 // of scalars and arrays of class type with trivial copy-assignment
7978 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00007979 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00007980 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007981 // Compute the size of the memory buffer to be copied.
7982 QualType SizeType = Context.getSizeType();
7983 llvm::APInt Size(Context.getTypeSize(SizeType),
7984 Context.getTypeSizeInChars(BaseType).getQuantity());
7985 for (const ConstantArrayType *Array
7986 = Context.getAsConstantArrayType(FieldType);
7987 Array;
7988 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00007989 llvm::APInt ArraySize
7990 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007991 Size *= ArraySize;
7992 }
7993
7994 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00007995 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7996 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007997
7998 bool NeedsCollectableMemCpy =
7999 (BaseType->isRecordType() &&
8000 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8001
8002 if (NeedsCollectableMemCpy) {
8003 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008004 // Create a reference to the __builtin_objc_memmove_collectable function.
8005 LookupResult R(*this,
8006 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008007 Loc, LookupOrdinaryName);
8008 LookupName(R, TUScope, true);
8009
8010 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8011 if (!CollectableMemCpy) {
8012 // Something went horribly wrong earlier, and we will have
8013 // complained about it.
8014 Invalid = true;
8015 continue;
8016 }
8017
8018 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8019 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008020 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008021 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8022 }
8023 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008024 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008025 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008026 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8027 LookupOrdinaryName);
8028 LookupName(R, TUScope, true);
8029
8030 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8031 if (!BuiltinMemCpy) {
8032 // Something went horribly wrong earlier, and we will have complained
8033 // about it.
8034 Invalid = true;
8035 continue;
8036 }
8037
8038 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8039 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008040 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008041 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8042 }
8043
John McCall37ad5512010-08-23 06:44:23 +00008044 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008045 CallArgs.push_back(To.takeAs<Expr>());
8046 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008047 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00008048 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008049 if (NeedsCollectableMemCpy)
8050 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008051 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008052 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008053 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008054 else
8055 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008056 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008057 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008058 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008059
Douglas Gregorb139cd52010-05-01 20:49:11 +00008060 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8061 Statements.push_back(Call.takeAs<Expr>());
8062 continue;
8063 }
8064
8065 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00008066 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008067 To.get(), From.get(),
8068 /*CopyingBaseSubobject=*/false,
8069 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008070 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008071 Diag(CurrentLocation, diag::note_member_synthesized_at)
8072 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8073 CopyAssignOperator->setInvalidDecl();
8074 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008075 }
8076
8077 // Success! Record the copy.
8078 Statements.push_back(Copy.takeAs<Stmt>());
8079 }
8080
8081 if (!Invalid) {
8082 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00008083 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008084
John McCalldadc5752010-08-24 06:29:42 +00008085 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008086 if (Return.isInvalid())
8087 Invalid = true;
8088 else {
8089 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00008090
8091 if (Trap.hasErrorOccurred()) {
8092 Diag(CurrentLocation, diag::note_member_synthesized_at)
8093 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8094 Invalid = true;
8095 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008096 }
8097 }
8098
8099 if (Invalid) {
8100 CopyAssignOperator->setInvalidDecl();
8101 return;
8102 }
8103
John McCalldadc5752010-08-24 06:29:42 +00008104 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00008105 /*isStmtExpr=*/false);
8106 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8107 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00008108
8109 if (ASTMutationListener *L = getASTMutationListener()) {
8110 L->CompletedImplicitDefinition(CopyAssignOperator);
8111 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008112}
8113
Sebastian Redl22653ba2011-08-30 19:58:05 +00008114Sema::ImplicitExceptionSpecification
8115Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8116 ImplicitExceptionSpecification ExceptSpec(Context);
8117
8118 if (ClassDecl->isInvalidDecl())
8119 return ExceptSpec;
8120
8121 // C++0x [except.spec]p14:
8122 // An implicitly declared special member function (Clause 12) shall have an
8123 // exception-specification. [...]
8124
8125 // It is unspecified whether or not an implicit move assignment operator
8126 // attempts to deduplicate calls to assignment operators of virtual bases are
8127 // made. As such, this exception specification is effectively unspecified.
8128 // Based on a similar decision made for constness in C++0x, we're erring on
8129 // the side of assuming such calls to be made regardless of whether they
8130 // actually happen.
8131 // Note that a move constructor is not implicitly declared when there are
8132 // virtual bases, but it can still be user-declared and explicitly defaulted.
8133 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8134 BaseEnd = ClassDecl->bases_end();
8135 Base != BaseEnd; ++Base) {
8136 if (Base->isVirtual())
8137 continue;
8138
8139 CXXRecordDecl *BaseClassDecl
8140 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8141 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8142 false, 0))
8143 ExceptSpec.CalledDecl(MoveAssign);
8144 }
8145
8146 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8147 BaseEnd = ClassDecl->vbases_end();
8148 Base != BaseEnd; ++Base) {
8149 CXXRecordDecl *BaseClassDecl
8150 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8151 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8152 false, 0))
8153 ExceptSpec.CalledDecl(MoveAssign);
8154 }
8155
8156 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8157 FieldEnd = ClassDecl->field_end();
8158 Field != FieldEnd;
8159 ++Field) {
8160 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8161 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8162 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8163 false, 0))
8164 ExceptSpec.CalledDecl(MoveAssign);
8165 }
8166 }
8167
8168 return ExceptSpec;
8169}
8170
8171CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8172 // Note: The following rules are largely analoguous to the move
8173 // constructor rules.
8174
8175 ImplicitExceptionSpecification Spec(
8176 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8177
8178 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8179 QualType RetType = Context.getLValueReferenceType(ArgType);
8180 ArgType = Context.getRValueReferenceType(ArgType);
8181
8182 // An implicitly-declared move assignment operator is an inline public
8183 // member of its class.
8184 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8185 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8186 SourceLocation ClassLoc = ClassDecl->getLocation();
8187 DeclarationNameInfo NameInfo(Name, ClassLoc);
8188 CXXMethodDecl *MoveAssignment
8189 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8190 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8191 /*TInfo=*/0, /*isStatic=*/false,
8192 /*StorageClassAsWritten=*/SC_None,
8193 /*isInline=*/true,
8194 /*isConstexpr=*/false,
8195 SourceLocation());
8196 MoveAssignment->setAccess(AS_public);
8197 MoveAssignment->setDefaulted();
8198 MoveAssignment->setImplicit();
8199 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8200
8201 // Add the parameter to the operator.
8202 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8203 ClassLoc, ClassLoc, /*Id=*/0,
8204 ArgType, /*TInfo=*/0,
8205 SC_None,
8206 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008207 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008208
8209 // Note that we have added this copy-assignment operator.
8210 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8211
8212 // C++0x [class.copy]p9:
8213 // If the definition of a class X does not explicitly declare a move
8214 // assignment operator, one will be implicitly declared as defaulted if and
8215 // only if:
8216 // [...]
8217 // - the move assignment operator would not be implicitly defined as
8218 // deleted.
8219 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8220 // Cache this result so that we don't try to generate this over and over
8221 // on every lookup, leaking memory and wasting time.
8222 ClassDecl->setFailedImplicitMoveAssignment();
8223 return 0;
8224 }
8225
8226 if (Scope *S = getScopeForContext(ClassDecl))
8227 PushOnScopeChains(MoveAssignment, S, false);
8228 ClassDecl->addDecl(MoveAssignment);
8229
8230 AddOverriddenMethods(ClassDecl, MoveAssignment);
8231 return MoveAssignment;
8232}
8233
8234void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8235 CXXMethodDecl *MoveAssignOperator) {
8236 assert((MoveAssignOperator->isDefaulted() &&
8237 MoveAssignOperator->isOverloadedOperator() &&
8238 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8239 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8240 "DefineImplicitMoveAssignment called for wrong function");
8241
8242 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8243
8244 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8245 MoveAssignOperator->setInvalidDecl();
8246 return;
8247 }
8248
8249 MoveAssignOperator->setUsed();
8250
8251 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8252 DiagnosticErrorTrap Trap(Diags);
8253
8254 // C++0x [class.copy]p28:
8255 // The implicitly-defined or move assignment operator for a non-union class
8256 // X performs memberwise move assignment of its subobjects. The direct base
8257 // classes of X are assigned first, in the order of their declaration in the
8258 // base-specifier-list, and then the immediate non-static data members of X
8259 // are assigned, in the order in which they were declared in the class
8260 // definition.
8261
8262 // The statements that form the synthesized function body.
8263 ASTOwningVector<Stmt*> Statements(*this);
8264
8265 // The parameter for the "other" object, which we are move from.
8266 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8267 QualType OtherRefType = Other->getType()->
8268 getAs<RValueReferenceType>()->getPointeeType();
8269 assert(OtherRefType.getQualifiers() == 0 &&
8270 "Bad argument type of defaulted move assignment");
8271
8272 // Our location for everything implicitly-generated.
8273 SourceLocation Loc = MoveAssignOperator->getLocation();
8274
8275 // Construct a reference to the "other" object. We'll be using this
8276 // throughout the generated ASTs.
8277 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8278 assert(OtherRef && "Reference to parameter cannot fail!");
8279 // Cast to rvalue.
8280 OtherRef = CastForMoving(*this, OtherRef);
8281
8282 // Construct the "this" pointer. We'll be using this throughout the generated
8283 // ASTs.
8284 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8285 assert(This && "Reference to this cannot fail!");
8286
8287 // Assign base classes.
8288 bool Invalid = false;
8289 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8290 E = ClassDecl->bases_end(); Base != E; ++Base) {
8291 // Form the assignment:
8292 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8293 QualType BaseType = Base->getType().getUnqualifiedType();
8294 if (!BaseType->isRecordType()) {
8295 Invalid = true;
8296 continue;
8297 }
8298
8299 CXXCastPath BasePath;
8300 BasePath.push_back(Base);
8301
8302 // Construct the "from" expression, which is an implicit cast to the
8303 // appropriately-qualified base type.
8304 Expr *From = OtherRef;
8305 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00008306 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00008307
8308 // Dereference "this".
8309 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8310
8311 // Implicitly cast "this" to the appropriately-qualified base type.
8312 To = ImpCastExprToType(To.take(),
8313 Context.getCVRQualifiedType(BaseType,
8314 MoveAssignOperator->getTypeQualifiers()),
8315 CK_UncheckedDerivedToBase,
8316 VK_LValue, &BasePath);
8317
8318 // Build the move.
8319 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8320 To.get(), From,
8321 /*CopyingBaseSubobject=*/true,
8322 /*Copying=*/false);
8323 if (Move.isInvalid()) {
8324 Diag(CurrentLocation, diag::note_member_synthesized_at)
8325 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8326 MoveAssignOperator->setInvalidDecl();
8327 return;
8328 }
8329
8330 // Success! Record the move.
8331 Statements.push_back(Move.takeAs<Expr>());
8332 }
8333
8334 // \brief Reference to the __builtin_memcpy function.
8335 Expr *BuiltinMemCpyRef = 0;
8336 // \brief Reference to the __builtin_objc_memmove_collectable function.
8337 Expr *CollectableMemCpyRef = 0;
8338
8339 // Assign non-static members.
8340 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8341 FieldEnd = ClassDecl->field_end();
8342 Field != FieldEnd; ++Field) {
8343 // Check for members of reference type; we can't move those.
8344 if (Field->getType()->isReferenceType()) {
8345 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8346 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8347 Diag(Field->getLocation(), diag::note_declared_at);
8348 Diag(CurrentLocation, diag::note_member_synthesized_at)
8349 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8350 Invalid = true;
8351 continue;
8352 }
8353
8354 // Check for members of const-qualified, non-class type.
8355 QualType BaseType = Context.getBaseElementType(Field->getType());
8356 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8357 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8358 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8359 Diag(Field->getLocation(), diag::note_declared_at);
8360 Diag(CurrentLocation, diag::note_member_synthesized_at)
8361 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8362 Invalid = true;
8363 continue;
8364 }
8365
8366 // Suppress assigning zero-width bitfields.
8367 if (const Expr *Width = Field->getBitWidth())
8368 if (Width->EvaluateAsInt(Context) == 0)
8369 continue;
8370
8371 QualType FieldType = Field->getType().getNonReferenceType();
8372 if (FieldType->isIncompleteArrayType()) {
8373 assert(ClassDecl->hasFlexibleArrayMember() &&
8374 "Incomplete array type is not valid");
8375 continue;
8376 }
8377
8378 // Build references to the field in the object we're copying from and to.
8379 CXXScopeSpec SS; // Intentionally empty
8380 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8381 LookupMemberName);
8382 MemberLookup.addDecl(*Field);
8383 MemberLookup.resolveKind();
8384 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8385 Loc, /*IsArrow=*/false,
8386 SS, 0, MemberLookup, 0);
8387 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8388 Loc, /*IsArrow=*/true,
8389 SS, 0, MemberLookup, 0);
8390 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8391 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8392
8393 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8394 "Member reference with rvalue base must be rvalue except for reference "
8395 "members, which aren't allowed for move assignment.");
8396
8397 // If the field should be copied with __builtin_memcpy rather than via
8398 // explicit assignments, do so. This optimization only applies for arrays
8399 // of scalars and arrays of class type with trivial move-assignment
8400 // operators.
8401 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8402 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8403 // Compute the size of the memory buffer to be copied.
8404 QualType SizeType = Context.getSizeType();
8405 llvm::APInt Size(Context.getTypeSize(SizeType),
8406 Context.getTypeSizeInChars(BaseType).getQuantity());
8407 for (const ConstantArrayType *Array
8408 = Context.getAsConstantArrayType(FieldType);
8409 Array;
8410 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8411 llvm::APInt ArraySize
8412 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8413 Size *= ArraySize;
8414 }
8415
Douglas Gregor528499b2011-09-01 02:09:07 +00008416 // Take the address of the field references for "from" and "to". We
8417 // directly construct UnaryOperators here because semantic analysis
8418 // does not permit us to take the address of an xvalue.
8419 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8420 Context.getPointerType(From.get()->getType()),
8421 VK_RValue, OK_Ordinary, Loc);
8422 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8423 Context.getPointerType(To.get()->getType()),
8424 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008425
8426 bool NeedsCollectableMemCpy =
8427 (BaseType->isRecordType() &&
8428 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8429
8430 if (NeedsCollectableMemCpy) {
8431 if (!CollectableMemCpyRef) {
8432 // Create a reference to the __builtin_objc_memmove_collectable function.
8433 LookupResult R(*this,
8434 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8435 Loc, LookupOrdinaryName);
8436 LookupName(R, TUScope, true);
8437
8438 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8439 if (!CollectableMemCpy) {
8440 // Something went horribly wrong earlier, and we will have
8441 // complained about it.
8442 Invalid = true;
8443 continue;
8444 }
8445
8446 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8447 CollectableMemCpy->getType(),
8448 VK_LValue, Loc, 0).take();
8449 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8450 }
8451 }
8452 // Create a reference to the __builtin_memcpy builtin function.
8453 else if (!BuiltinMemCpyRef) {
8454 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8455 LookupOrdinaryName);
8456 LookupName(R, TUScope, true);
8457
8458 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8459 if (!BuiltinMemCpy) {
8460 // Something went horribly wrong earlier, and we will have complained
8461 // about it.
8462 Invalid = true;
8463 continue;
8464 }
8465
8466 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8467 BuiltinMemCpy->getType(),
8468 VK_LValue, Loc, 0).take();
8469 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8470 }
8471
8472 ASTOwningVector<Expr*> CallArgs(*this);
8473 CallArgs.push_back(To.takeAs<Expr>());
8474 CallArgs.push_back(From.takeAs<Expr>());
8475 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8476 ExprResult Call = ExprError();
8477 if (NeedsCollectableMemCpy)
8478 Call = ActOnCallExpr(/*Scope=*/0,
8479 CollectableMemCpyRef,
8480 Loc, move_arg(CallArgs),
8481 Loc);
8482 else
8483 Call = ActOnCallExpr(/*Scope=*/0,
8484 BuiltinMemCpyRef,
8485 Loc, move_arg(CallArgs),
8486 Loc);
8487
8488 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8489 Statements.push_back(Call.takeAs<Expr>());
8490 continue;
8491 }
8492
8493 // Build the move of this field.
8494 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8495 To.get(), From.get(),
8496 /*CopyingBaseSubobject=*/false,
8497 /*Copying=*/false);
8498 if (Move.isInvalid()) {
8499 Diag(CurrentLocation, diag::note_member_synthesized_at)
8500 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8501 MoveAssignOperator->setInvalidDecl();
8502 return;
8503 }
8504
8505 // Success! Record the copy.
8506 Statements.push_back(Move.takeAs<Stmt>());
8507 }
8508
8509 if (!Invalid) {
8510 // Add a "return *this;"
8511 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8512
8513 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8514 if (Return.isInvalid())
8515 Invalid = true;
8516 else {
8517 Statements.push_back(Return.takeAs<Stmt>());
8518
8519 if (Trap.hasErrorOccurred()) {
8520 Diag(CurrentLocation, diag::note_member_synthesized_at)
8521 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8522 Invalid = true;
8523 }
8524 }
8525 }
8526
8527 if (Invalid) {
8528 MoveAssignOperator->setInvalidDecl();
8529 return;
8530 }
8531
8532 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8533 /*isStmtExpr=*/false);
8534 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8535 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8536
8537 if (ASTMutationListener *L = getASTMutationListener()) {
8538 L->CompletedImplicitDefinition(MoveAssignOperator);
8539 }
8540}
8541
Alexis Hunt913820d2011-05-13 06:10:58 +00008542std::pair<Sema::ImplicitExceptionSpecification, bool>
8543Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008544 if (ClassDecl->isInvalidDecl())
8545 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8546
Douglas Gregor54be3392010-07-01 17:57:27 +00008547 // C++ [class.copy]p5:
8548 // The implicitly-declared copy constructor for a class X will
8549 // have the form
8550 //
8551 // X::X(const X&)
8552 //
8553 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008554 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008555 bool HasConstCopyConstructor = true;
8556
8557 // -- each direct or virtual base class B of X has a copy
8558 // constructor whose first parameter is of type const B& or
8559 // const volatile B&, and
8560 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8561 BaseEnd = ClassDecl->bases_end();
8562 HasConstCopyConstructor && Base != BaseEnd;
8563 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008564 // Virtual bases are handled below.
8565 if (Base->isVirtual())
8566 continue;
8567
Douglas Gregora6d69502010-07-02 23:41:54 +00008568 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008569 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008570 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8571 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008572 }
8573
8574 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8575 BaseEnd = ClassDecl->vbases_end();
8576 HasConstCopyConstructor && Base != BaseEnd;
8577 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008578 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008579 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008580 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8581 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008582 }
8583
8584 // -- for all the nonstatic data members of X that are of a
8585 // class type M (or array thereof), each such class type
8586 // has a copy constructor whose first parameter is of type
8587 // const M& or const volatile M&.
8588 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8589 FieldEnd = ClassDecl->field_end();
8590 HasConstCopyConstructor && Field != FieldEnd;
8591 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008592 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008593 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008594 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8595 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008596 }
8597 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008598 // Otherwise, the implicitly declared copy constructor will have
8599 // the form
8600 //
8601 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008602
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008603 // C++ [except.spec]p14:
8604 // An implicitly declared special member function (Clause 12) shall have an
8605 // exception-specification. [...]
8606 ImplicitExceptionSpecification ExceptSpec(Context);
8607 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8608 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8609 BaseEnd = ClassDecl->bases_end();
8610 Base != BaseEnd;
8611 ++Base) {
8612 // Virtual bases are handled below.
8613 if (Base->isVirtual())
8614 continue;
8615
Douglas Gregora6d69502010-07-02 23:41:54 +00008616 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008617 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008618 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008619 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008620 ExceptSpec.CalledDecl(CopyConstructor);
8621 }
8622 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8623 BaseEnd = ClassDecl->vbases_end();
8624 Base != BaseEnd;
8625 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008626 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008627 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008628 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008629 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008630 ExceptSpec.CalledDecl(CopyConstructor);
8631 }
8632 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8633 FieldEnd = ClassDecl->field_end();
8634 Field != FieldEnd;
8635 ++Field) {
8636 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008637 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8638 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008639 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008640 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008641 }
8642 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008643
Alexis Hunt913820d2011-05-13 06:10:58 +00008644 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8645}
8646
8647CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8648 CXXRecordDecl *ClassDecl) {
8649 // C++ [class.copy]p4:
8650 // If the class definition does not explicitly declare a copy
8651 // constructor, one is declared implicitly.
8652
8653 ImplicitExceptionSpecification Spec(Context);
8654 bool Const;
8655 llvm::tie(Spec, Const) =
8656 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8657
8658 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8659 QualType ArgType = ClassType;
8660 if (Const)
8661 ArgType = ArgType.withConst();
8662 ArgType = Context.getLValueReferenceType(ArgType);
8663
8664 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8665
Douglas Gregor54be3392010-07-01 17:57:27 +00008666 DeclarationName Name
8667 = Context.DeclarationNames.getCXXConstructorName(
8668 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008669 SourceLocation ClassLoc = ClassDecl->getLocation();
8670 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008671
8672 // An implicitly-declared copy constructor is an inline public
8673 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00008674 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00008675 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00008676 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00008677 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00008678 /*TInfo=*/0,
8679 /*isExplicit=*/false,
8680 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00008681 /*isImplicitlyDeclared=*/true,
8682 // FIXME: apply the rules for definitions here
8683 /*isConstexpr=*/false);
Douglas Gregor54be3392010-07-01 17:57:27 +00008684 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008685 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008686 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8687
Douglas Gregora6d69502010-07-02 23:41:54 +00008688 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008689 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8690
Douglas Gregor54be3392010-07-01 17:57:27 +00008691 // Add the parameter to the constructor.
8692 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008693 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008694 /*IdentifierInfo=*/0,
8695 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008696 SC_None,
8697 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008698 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008699
Douglas Gregor0be31a22010-07-02 17:43:08 +00008700 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008701 PushOnScopeChains(CopyConstructor, S, false);
8702 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008703
Alexis Huntd74c85f2011-06-22 01:05:13 +00008704 // C++0x [class.copy]p7:
8705 // ... If the class definition declares a move constructor or move
8706 // assignment operator, the implicitly declared constructor is defined as
8707 // deleted; ...
8708 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8709 ClassDecl->hasUserDeclaredMoveAssignment() ||
8710 ShouldDeleteCopyConstructor(CopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008711 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008712
8713 return CopyConstructor;
8714}
8715
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008716void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008717 CXXConstructorDecl *CopyConstructor) {
8718 assert((CopyConstructor->isDefaulted() &&
8719 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008720 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008721 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008722
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008723 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008724 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008725
Douglas Gregora57478e2010-05-01 15:04:51 +00008726 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008727 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008728
Alexis Hunt1d792652011-01-08 20:30:50 +00008729 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008730 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008731 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008732 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008733 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008734 } else {
8735 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8736 CopyConstructor->getLocation(),
8737 MultiStmtArg(*this, 0, 0),
8738 /*isStmtExpr=*/false)
8739 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008740 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008741 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008742
8743 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008744 if (ASTMutationListener *L = getASTMutationListener()) {
8745 L->CompletedImplicitDefinition(CopyConstructor);
8746 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008747}
8748
Sebastian Redl22653ba2011-08-30 19:58:05 +00008749Sema::ImplicitExceptionSpecification
8750Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8751 // C++ [except.spec]p14:
8752 // An implicitly declared special member function (Clause 12) shall have an
8753 // exception-specification. [...]
8754 ImplicitExceptionSpecification ExceptSpec(Context);
8755 if (ClassDecl->isInvalidDecl())
8756 return ExceptSpec;
8757
8758 // Direct base-class constructors.
8759 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8760 BEnd = ClassDecl->bases_end();
8761 B != BEnd; ++B) {
8762 if (B->isVirtual()) // Handled below.
8763 continue;
8764
8765 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8766 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8767 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8768 // If this is a deleted function, add it anyway. This might be conformant
8769 // with the standard. This might not. I'm not sure. It might not matter.
8770 if (Constructor)
8771 ExceptSpec.CalledDecl(Constructor);
8772 }
8773 }
8774
8775 // Virtual base-class constructors.
8776 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8777 BEnd = ClassDecl->vbases_end();
8778 B != BEnd; ++B) {
8779 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8780 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8781 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8782 // If this is a deleted function, add it anyway. This might be conformant
8783 // with the standard. This might not. I'm not sure. It might not matter.
8784 if (Constructor)
8785 ExceptSpec.CalledDecl(Constructor);
8786 }
8787 }
8788
8789 // Field constructors.
8790 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8791 FEnd = ClassDecl->field_end();
8792 F != FEnd; ++F) {
8793 if (F->hasInClassInitializer()) {
8794 if (Expr *E = F->getInClassInitializer())
8795 ExceptSpec.CalledExpr(E);
8796 else if (!F->isInvalidDecl())
8797 ExceptSpec.SetDelayed();
8798 } else if (const RecordType *RecordTy
8799 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8800 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8801 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8802 // If this is a deleted function, add it anyway. This might be conformant
8803 // with the standard. This might not. I'm not sure. It might not matter.
8804 // In particular, the problem is that this function never gets called. It
8805 // might just be ill-formed because this function attempts to refer to
8806 // a deleted function here.
8807 if (Constructor)
8808 ExceptSpec.CalledDecl(Constructor);
8809 }
8810 }
8811
8812 return ExceptSpec;
8813}
8814
8815CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8816 CXXRecordDecl *ClassDecl) {
8817 ImplicitExceptionSpecification Spec(
8818 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8819
8820 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8821 QualType ArgType = Context.getRValueReferenceType(ClassType);
8822
8823 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8824
8825 DeclarationName Name
8826 = Context.DeclarationNames.getCXXConstructorName(
8827 Context.getCanonicalType(ClassType));
8828 SourceLocation ClassLoc = ClassDecl->getLocation();
8829 DeclarationNameInfo NameInfo(Name, ClassLoc);
8830
8831 // C++0x [class.copy]p11:
8832 // An implicitly-declared copy/move constructor is an inline public
8833 // member of its class.
8834 CXXConstructorDecl *MoveConstructor
8835 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8836 Context.getFunctionType(Context.VoidTy,
8837 &ArgType, 1, EPI),
8838 /*TInfo=*/0,
8839 /*isExplicit=*/false,
8840 /*isInline=*/true,
8841 /*isImplicitlyDeclared=*/true,
8842 // FIXME: apply the rules for definitions here
8843 /*isConstexpr=*/false);
8844 MoveConstructor->setAccess(AS_public);
8845 MoveConstructor->setDefaulted();
8846 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8847
8848 // Add the parameter to the constructor.
8849 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8850 ClassLoc, ClassLoc,
8851 /*IdentifierInfo=*/0,
8852 ArgType, /*TInfo=*/0,
8853 SC_None,
8854 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008855 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008856
8857 // C++0x [class.copy]p9:
8858 // If the definition of a class X does not explicitly declare a move
8859 // constructor, one will be implicitly declared as defaulted if and only if:
8860 // [...]
8861 // - the move constructor would not be implicitly defined as deleted.
8862 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8863 // Cache this result so that we don't try to generate this over and over
8864 // on every lookup, leaking memory and wasting time.
8865 ClassDecl->setFailedImplicitMoveConstructor();
8866 return 0;
8867 }
8868
8869 // Note that we have declared this constructor.
8870 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8871
8872 if (Scope *S = getScopeForContext(ClassDecl))
8873 PushOnScopeChains(MoveConstructor, S, false);
8874 ClassDecl->addDecl(MoveConstructor);
8875
8876 return MoveConstructor;
8877}
8878
8879void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8880 CXXConstructorDecl *MoveConstructor) {
8881 assert((MoveConstructor->isDefaulted() &&
8882 MoveConstructor->isMoveConstructor() &&
8883 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8884 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8885
8886 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8887 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8888
8889 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8890 DiagnosticErrorTrap Trap(Diags);
8891
8892 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8893 Trap.hasErrorOccurred()) {
8894 Diag(CurrentLocation, diag::note_member_synthesized_at)
8895 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8896 MoveConstructor->setInvalidDecl();
8897 } else {
8898 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8899 MoveConstructor->getLocation(),
8900 MultiStmtArg(*this, 0, 0),
8901 /*isStmtExpr=*/false)
8902 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008903 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008904 }
8905
8906 MoveConstructor->setUsed();
8907
8908 if (ASTMutationListener *L = getASTMutationListener()) {
8909 L->CompletedImplicitDefinition(MoveConstructor);
8910 }
8911}
8912
John McCalldadc5752010-08-24 06:29:42 +00008913ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008914Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00008915 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008916 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008917 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008918 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008919 unsigned ConstructKind,
8920 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00008921 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00008922
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008923 // C++0x [class.copy]p34:
8924 // When certain criteria are met, an implementation is allowed to
8925 // omit the copy/move construction of a class object, even if the
8926 // copy/move constructor and/or destructor for the object have
8927 // side effects. [...]
8928 // - when a temporary class object that has not been bound to a
8929 // reference (12.2) would be copied/moved to a class object
8930 // with the same cv-unqualified type, the copy/move operation
8931 // can be omitted by constructing the temporary object
8932 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00008933 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00008934 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008935 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00008936 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00008937 }
Mike Stump11289f42009-09-09 15:08:12 +00008938
8939 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008940 Elidable, move(ExprArgs), HadMultipleCandidates,
8941 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00008942}
8943
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008944/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8945/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00008946ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008947Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8948 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008949 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008950 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008951 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008952 unsigned ConstructKind,
8953 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00008954 unsigned NumExprs = ExprArgs.size();
8955 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00008956
Nick Lewyckyd4693212011-03-25 01:44:32 +00008957 for (specific_attr_iterator<NonNullAttr>
8958 i = Constructor->specific_attr_begin<NonNullAttr>(),
8959 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8960 const NonNullAttr *NonNull = *i;
8961 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8962 }
8963
Douglas Gregor27381f32009-11-23 12:27:39 +00008964 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00008965 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008966 Constructor, Elidable, Exprs, NumExprs,
8967 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008968 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8969 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008970}
8971
Mike Stump11289f42009-09-09 15:08:12 +00008972bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008973 CXXConstructorDecl *Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008974 MultiExprArg Exprs,
8975 bool HadMultipleCandidates) {
Chandler Carruth01718152010-10-25 08:47:36 +00008976 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00008977 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00008978 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008979 move(Exprs), HadMultipleCandidates, false,
8980 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008981 if (TempResult.isInvalid())
8982 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008983
Anders Carlsson6eb55572009-08-25 05:12:04 +00008984 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00008985 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00008986 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00008987 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00008988 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00008989
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008990 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00008991}
8992
John McCall03c48482010-02-02 09:10:11 +00008993void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00008994 if (VD->isInvalidDecl()) return;
8995
John McCall03c48482010-02-02 09:10:11 +00008996 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00008997 if (ClassDecl->isInvalidDecl()) return;
8998 if (ClassDecl->hasTrivialDestructor()) return;
8999 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00009000
Chandler Carruth86d17d32011-03-27 21:26:48 +00009001 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9002 MarkDeclarationReferenced(VD->getLocation(), Destructor);
9003 CheckDestructorAccess(VD->getLocation(), Destructor,
9004 PDiag(diag::err_access_dtor_var)
9005 << VD->getDeclName()
9006 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00009007
Chandler Carruth86d17d32011-03-27 21:26:48 +00009008 if (!VD->hasGlobalStorage()) return;
9009
9010 // Emit warning for non-trivial dtor in global scope (a real global,
9011 // class-static, function-static).
9012 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9013
9014 // TODO: this should be re-enabled for static locals by !CXAAtExit
9015 if (!VD->isStaticLocal())
9016 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009017}
9018
Mike Stump11289f42009-09-09 15:08:12 +00009019/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009020/// ActOnDeclarator, when a C++ direct initializer is present.
9021/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00009022void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00009023 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009024 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00009025 SourceLocation RParenLoc,
9026 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00009027 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009028
9029 // If there is no declaration, there was an error parsing it. Just ignore
9030 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00009031 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009032 return;
Mike Stump11289f42009-09-09 15:08:12 +00009033
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009034 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9035 if (!VDecl) {
9036 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9037 RealDecl->setInvalidDecl();
9038 return;
9039 }
9040
Richard Smith30482bc2011-02-20 03:19:35 +00009041 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9042 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009043 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
9044 if (Exprs.size() > 1) {
9045 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9046 diag::err_auto_var_init_multiple_expressions)
9047 << VDecl->getDeclName() << VDecl->getType()
9048 << VDecl->getSourceRange();
9049 RealDecl->setInvalidDecl();
9050 return;
9051 }
9052
9053 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00009054 TypeSourceInfo *DeducedType = 0;
9055 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00009056 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
9057 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
9058 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00009059 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00009060 RealDecl->setInvalidDecl();
9061 return;
9062 }
Richard Smith9647d3c2011-03-17 16:11:59 +00009063 VDecl->setTypeSourceInfo(DeducedType);
9064 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00009065
John McCall31168b02011-06-15 23:02:42 +00009066 // In ARC, infer lifetime.
9067 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9068 VDecl->setInvalidDecl();
9069
Richard Smith30482bc2011-02-20 03:19:35 +00009070 // If this is a redeclaration, check that the type we just deduced matches
9071 // the previously declared type.
9072 if (VarDecl *Old = VDecl->getPreviousDeclaration())
9073 MergeVarDeclTypes(VDecl, Old);
9074 }
9075
Douglas Gregor402250f2009-08-26 21:14:46 +00009076 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009077 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009078 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9079 //
9080 // Clients that want to distinguish between the two forms, can check for
9081 // direct initializer using VarDecl::hasCXXDirectInitializer().
9082 // A major benefit is that clients that don't particularly care about which
9083 // exactly form was it (like the CodeGen) can handle both cases without
9084 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009085
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009086 // C++ 8.5p11:
9087 // The form of initialization (using parentheses or '=') is generally
9088 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009089 // class type.
9090
Douglas Gregor50dc2192010-02-11 22:55:30 +00009091 if (!VDecl->getType()->isDependentType() &&
Douglas Gregorb06fa542011-10-10 16:05:18 +00009092 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor50dc2192010-02-11 22:55:30 +00009093 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00009094 diag::err_typecheck_decl_incomplete_type)) {
9095 VDecl->setInvalidDecl();
9096 return;
9097 }
9098
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009099 // The variable can not have an abstract class type.
9100 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9101 diag::err_abstract_type_in_decl,
9102 AbstractVariableType))
9103 VDecl->setInvalidDecl();
9104
Sebastian Redl5ca79842010-02-01 20:16:42 +00009105 const VarDecl *Def;
9106 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009107 Diag(VDecl->getLocation(), diag::err_redefinition)
9108 << VDecl->getDeclName();
9109 Diag(Def->getLocation(), diag::note_previous_definition);
9110 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009111 return;
9112 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00009113
Douglas Gregorf0f83692010-08-24 05:27:49 +00009114 // C++ [class.static.data]p4
9115 // If a static data member is of const integral or const
9116 // enumeration type, its declaration in the class definition can
9117 // specify a constant-initializer which shall be an integral
9118 // constant expression (5.19). In that case, the member can appear
9119 // in integral constant expressions. The member shall still be
9120 // defined in a namespace scope if it is used in the program and the
9121 // namespace scope definition shall not contain an initializer.
9122 //
9123 // We already performed a redefinition check above, but for static
9124 // data members we also need to check whether there was an in-class
9125 // declaration with an initializer.
9126 const VarDecl* PrevInit = 0;
9127 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9128 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9129 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9130 return;
9131 }
9132
Douglas Gregor71f39c92010-12-16 01:31:22 +00009133 bool IsDependent = false;
9134 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9135 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9136 VDecl->setInvalidDecl();
9137 return;
9138 }
9139
9140 if (Exprs.get()[I]->isTypeDependent())
9141 IsDependent = true;
9142 }
9143
Douglas Gregor50dc2192010-02-11 22:55:30 +00009144 // If either the declaration has a dependent type or if any of the
9145 // expressions is type-dependent, we represent the initialization
9146 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00009147 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00009148 // Let clients know that initialization was done with a direct initializer.
9149 VDecl->setCXXDirectInitializer(true);
9150
9151 // Store the initialization expressions as a ParenListExpr.
9152 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00009153 VDecl->setInit(new (Context) ParenListExpr(
9154 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9155 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00009156 return;
9157 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009158
9159 // Capture the variable that is being initialized and the style of
9160 // initialization.
9161 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9162
9163 // FIXME: Poor source location information.
9164 InitializationKind Kind
9165 = InitializationKind::CreateDirect(VDecl->getLocation(),
9166 LParenLoc, RParenLoc);
9167
Douglas Gregorb06fa542011-10-10 16:05:18 +00009168 QualType T = VDecl->getType();
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009169 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00009170 Exprs.get(), Exprs.size());
Douglas Gregorb06fa542011-10-10 16:05:18 +00009171 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009172 if (Result.isInvalid()) {
9173 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009174 return;
Douglas Gregorb06fa542011-10-10 16:05:18 +00009175 } else if (T != VDecl->getType()) {
9176 VDecl->setType(T);
9177 Result.get()->setType(T);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009178 }
John McCallacf0ee52010-10-08 02:01:28 +00009179
Douglas Gregorb06fa542011-10-10 16:05:18 +00009180
Richard Smith2316cd82011-09-29 19:11:37 +00009181 Expr *Init = Result.get();
9182 CheckImplicitConversions(Init, LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009183
Richard Smith2316cd82011-09-29 19:11:37 +00009184 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
9185 !Init->isValueDependent() &&
9186 !Init->isConstantInitializer(Context,
9187 VDecl->getType()->isReferenceType())) {
9188 // FIXME: Improve this diagnostic to explain why the initializer is not
9189 // a constant expression.
9190 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
9191 << VDecl << Init->getSourceRange();
9192 }
9193
9194 Init = MaybeCreateExprWithCleanups(Init);
9195 VDecl->setInit(Init);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009196 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009197
John McCall8b7fd8f12011-01-19 11:48:09 +00009198 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009199}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009200
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009201/// \brief Given a constructor and the set of arguments provided for the
9202/// constructor, convert the arguments and add any required default arguments
9203/// to form a proper call to this constructor.
9204///
9205/// \returns true if an error occurred, false otherwise.
9206bool
9207Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9208 MultiExprArg ArgsPtr,
9209 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00009210 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009211 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9212 unsigned NumArgs = ArgsPtr.size();
9213 Expr **Args = (Expr **)ArgsPtr.get();
9214
9215 const FunctionProtoType *Proto
9216 = Constructor->getType()->getAs<FunctionProtoType>();
9217 assert(Proto && "Constructor without a prototype?");
9218 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009219
9220 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009221 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009222 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009223 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009224 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009225
9226 VariadicCallType CallType =
9227 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009228 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009229 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9230 Proto, 0, Args, NumArgs, AllArgs,
9231 CallType);
9232 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9233 ConvertedArgs.push_back(AllArgs[i]);
9234 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009235}
9236
Anders Carlssone363c8e2009-12-12 00:32:00 +00009237static inline bool
9238CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9239 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009240 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00009241 if (isa<NamespaceDecl>(DC)) {
9242 return SemaRef.Diag(FnDecl->getLocation(),
9243 diag::err_operator_new_delete_declared_in_namespace)
9244 << FnDecl->getDeclName();
9245 }
9246
9247 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00009248 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009249 return SemaRef.Diag(FnDecl->getLocation(),
9250 diag::err_operator_new_delete_declared_static)
9251 << FnDecl->getDeclName();
9252 }
9253
Anders Carlsson60659a82009-12-12 02:43:16 +00009254 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00009255}
9256
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009257static inline bool
9258CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9259 CanQualType ExpectedResultType,
9260 CanQualType ExpectedFirstParamType,
9261 unsigned DependentParamTypeDiag,
9262 unsigned InvalidParamTypeDiag) {
9263 QualType ResultType =
9264 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9265
9266 // Check that the result type is not dependent.
9267 if (ResultType->isDependentType())
9268 return SemaRef.Diag(FnDecl->getLocation(),
9269 diag::err_operator_new_delete_dependent_result_type)
9270 << FnDecl->getDeclName() << ExpectedResultType;
9271
9272 // Check that the result type is what we expect.
9273 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9274 return SemaRef.Diag(FnDecl->getLocation(),
9275 diag::err_operator_new_delete_invalid_result_type)
9276 << FnDecl->getDeclName() << ExpectedResultType;
9277
9278 // A function template must have at least 2 parameters.
9279 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9280 return SemaRef.Diag(FnDecl->getLocation(),
9281 diag::err_operator_new_delete_template_too_few_parameters)
9282 << FnDecl->getDeclName();
9283
9284 // The function decl must have at least 1 parameter.
9285 if (FnDecl->getNumParams() == 0)
9286 return SemaRef.Diag(FnDecl->getLocation(),
9287 diag::err_operator_new_delete_too_few_parameters)
9288 << FnDecl->getDeclName();
9289
9290 // Check the the first parameter type is not dependent.
9291 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9292 if (FirstParamType->isDependentType())
9293 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9294 << FnDecl->getDeclName() << ExpectedFirstParamType;
9295
9296 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00009297 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009298 ExpectedFirstParamType)
9299 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9300 << FnDecl->getDeclName() << ExpectedFirstParamType;
9301
9302 return false;
9303}
9304
Anders Carlsson12308f42009-12-11 23:23:22 +00009305static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009306CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009307 // C++ [basic.stc.dynamic.allocation]p1:
9308 // A program is ill-formed if an allocation function is declared in a
9309 // namespace scope other than global scope or declared static in global
9310 // scope.
9311 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9312 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009313
9314 CanQualType SizeTy =
9315 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9316
9317 // C++ [basic.stc.dynamic.allocation]p1:
9318 // The return type shall be void*. The first parameter shall have type
9319 // std::size_t.
9320 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9321 SizeTy,
9322 diag::err_operator_new_dependent_param_type,
9323 diag::err_operator_new_param_type))
9324 return true;
9325
9326 // C++ [basic.stc.dynamic.allocation]p1:
9327 // The first parameter shall not have an associated default argument.
9328 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00009329 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009330 diag::err_operator_new_default_arg)
9331 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9332
9333 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00009334}
9335
9336static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00009337CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9338 // C++ [basic.stc.dynamic.deallocation]p1:
9339 // A program is ill-formed if deallocation functions are declared in a
9340 // namespace scope other than global scope or declared static in global
9341 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00009342 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9343 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009344
9345 // C++ [basic.stc.dynamic.deallocation]p2:
9346 // Each deallocation function shall return void and its first parameter
9347 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009348 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9349 SemaRef.Context.VoidPtrTy,
9350 diag::err_operator_delete_dependent_param_type,
9351 diag::err_operator_delete_param_type))
9352 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009353
Anders Carlsson12308f42009-12-11 23:23:22 +00009354 return false;
9355}
9356
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009357/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9358/// of this overloaded operator is well-formed. If so, returns false;
9359/// otherwise, emits appropriate diagnostics and returns true.
9360bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00009361 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009362 "Expected an overloaded operator declaration");
9363
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009364 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9365
Mike Stump11289f42009-09-09 15:08:12 +00009366 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009367 // The allocation and deallocation functions, operator new,
9368 // operator new[], operator delete and operator delete[], are
9369 // described completely in 3.7.3. The attributes and restrictions
9370 // found in the rest of this subclause do not apply to them unless
9371 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00009372 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00009373 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00009374
Anders Carlsson22f443f2009-12-12 00:26:23 +00009375 if (Op == OO_New || Op == OO_Array_New)
9376 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009377
9378 // C++ [over.oper]p6:
9379 // An operator function shall either be a non-static member
9380 // function or be a non-member function and have at least one
9381 // parameter whose type is a class, a reference to a class, an
9382 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00009383 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9384 if (MethodDecl->isStatic())
9385 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009386 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009387 } else {
9388 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00009389 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9390 ParamEnd = FnDecl->param_end();
9391 Param != ParamEnd; ++Param) {
9392 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00009393 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9394 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009395 ClassOrEnumParam = true;
9396 break;
9397 }
9398 }
9399
Douglas Gregord69246b2008-11-17 16:14:12 +00009400 if (!ClassOrEnumParam)
9401 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009402 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009403 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009404 }
9405
9406 // C++ [over.oper]p8:
9407 // An operator function cannot have default arguments (8.3.6),
9408 // except where explicitly stated below.
9409 //
Mike Stump11289f42009-09-09 15:08:12 +00009410 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009411 // (C++ [over.call]p1).
9412 if (Op != OO_Call) {
9413 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9414 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009415 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00009416 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00009417 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009418 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009419 }
9420 }
9421
Douglas Gregor6cf08062008-11-10 13:38:07 +00009422 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9423 { false, false, false }
9424#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9425 , { Unary, Binary, MemberOnly }
9426#include "clang/Basic/OperatorKinds.def"
9427 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009428
Douglas Gregor6cf08062008-11-10 13:38:07 +00009429 bool CanBeUnaryOperator = OperatorUses[Op][0];
9430 bool CanBeBinaryOperator = OperatorUses[Op][1];
9431 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009432
9433 // C++ [over.oper]p8:
9434 // [...] Operator functions cannot have more or fewer parameters
9435 // than the number required for the corresponding operator, as
9436 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00009437 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00009438 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009439 if (Op != OO_Call &&
9440 ((NumParams == 1 && !CanBeUnaryOperator) ||
9441 (NumParams == 2 && !CanBeBinaryOperator) ||
9442 (NumParams < 1) || (NumParams > 2))) {
9443 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009444 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00009445 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009446 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00009447 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009448 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009449 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00009450 assert(CanBeBinaryOperator &&
9451 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009452 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009453 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009454
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009455 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009456 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009457 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009458
Douglas Gregord69246b2008-11-17 16:14:12 +00009459 // Overloaded operators other than operator() cannot be variadic.
9460 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009461 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009462 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009463 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009464 }
9465
9466 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009467 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9468 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009469 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009470 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009471 }
9472
9473 // C++ [over.inc]p1:
9474 // The user-defined function called operator++ implements the
9475 // prefix and postfix ++ operator. If this function is a member
9476 // function with no parameters, or a non-member function with one
9477 // parameter of class or enumeration type, it defines the prefix
9478 // increment operator ++ for objects of that type. If the function
9479 // is a member function with one parameter (which shall be of type
9480 // int) or a non-member function with two parameters (the second
9481 // of which shall be of type int), it defines the postfix
9482 // increment operator ++ for objects of that type.
9483 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9484 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9485 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009486 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009487 ParamIsInt = BT->getKind() == BuiltinType::Int;
9488
Chris Lattner2b786902008-11-21 07:50:02 +00009489 if (!ParamIsInt)
9490 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009491 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009492 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009493 }
9494
Douglas Gregord69246b2008-11-17 16:14:12 +00009495 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009496}
Chris Lattner3b024a32008-12-17 07:09:26 +00009497
Alexis Huntc88db062010-01-13 09:01:02 +00009498/// CheckLiteralOperatorDeclaration - Check whether the declaration
9499/// of this literal operator function is well-formed. If so, returns
9500/// false; otherwise, emits appropriate diagnostics and returns true.
9501bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9502 DeclContext *DC = FnDecl->getDeclContext();
9503 Decl::Kind Kind = DC->getDeclKind();
9504 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9505 Kind != Decl::LinkageSpec) {
9506 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9507 << FnDecl->getDeclName();
9508 return true;
9509 }
9510
9511 bool Valid = false;
9512
Alexis Hunt7dd26172010-04-07 23:11:06 +00009513 // template <char...> type operator "" name() is the only valid template
9514 // signature, and the only valid signature with no parameters.
9515 if (FnDecl->param_size() == 0) {
9516 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9517 // Must have only one template parameter
9518 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9519 if (Params->size() == 1) {
9520 NonTypeTemplateParmDecl *PmDecl =
9521 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009522
Alexis Hunt7dd26172010-04-07 23:11:06 +00009523 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009524 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9525 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9526 Valid = true;
9527 }
9528 }
9529 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009530 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009531 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9532
Alexis Huntc88db062010-01-13 09:01:02 +00009533 QualType T = (*Param)->getType();
9534
Alexis Hunt079a6f72010-04-07 22:57:35 +00009535 // unsigned long long int, long double, and any character type are allowed
9536 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009537 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9538 Context.hasSameType(T, Context.LongDoubleTy) ||
9539 Context.hasSameType(T, Context.CharTy) ||
9540 Context.hasSameType(T, Context.WCharTy) ||
9541 Context.hasSameType(T, Context.Char16Ty) ||
9542 Context.hasSameType(T, Context.Char32Ty)) {
9543 if (++Param == FnDecl->param_end())
9544 Valid = true;
9545 goto FinishedParams;
9546 }
9547
Alexis Hunt079a6f72010-04-07 22:57:35 +00009548 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009549 const PointerType *PT = T->getAs<PointerType>();
9550 if (!PT)
9551 goto FinishedParams;
9552 T = PT->getPointeeType();
9553 if (!T.isConstQualified())
9554 goto FinishedParams;
9555 T = T.getUnqualifiedType();
9556
9557 // Move on to the second parameter;
9558 ++Param;
9559
9560 // If there is no second parameter, the first must be a const char *
9561 if (Param == FnDecl->param_end()) {
9562 if (Context.hasSameType(T, Context.CharTy))
9563 Valid = true;
9564 goto FinishedParams;
9565 }
9566
9567 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9568 // are allowed as the first parameter to a two-parameter function
9569 if (!(Context.hasSameType(T, Context.CharTy) ||
9570 Context.hasSameType(T, Context.WCharTy) ||
9571 Context.hasSameType(T, Context.Char16Ty) ||
9572 Context.hasSameType(T, Context.Char32Ty)))
9573 goto FinishedParams;
9574
9575 // The second and final parameter must be an std::size_t
9576 T = (*Param)->getType().getUnqualifiedType();
9577 if (Context.hasSameType(T, Context.getSizeType()) &&
9578 ++Param == FnDecl->param_end())
9579 Valid = true;
9580 }
9581
9582 // FIXME: This diagnostic is absolutely terrible.
9583FinishedParams:
9584 if (!Valid) {
9585 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9586 << FnDecl->getDeclName();
9587 return true;
9588 }
9589
Douglas Gregor86325ad2011-08-30 22:40:35 +00009590 StringRef LiteralName
9591 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9592 if (LiteralName[0] != '_') {
9593 // C++0x [usrlit.suffix]p1:
9594 // Literal suffix identifiers that do not start with an underscore are
9595 // reserved for future standardization.
9596 bool IsHexFloat = true;
9597 if (LiteralName.size() > 1 &&
9598 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9599 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9600 if (!isdigit(LiteralName[I])) {
9601 IsHexFloat = false;
9602 break;
9603 }
9604 }
9605 }
9606
9607 if (IsHexFloat)
9608 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9609 << LiteralName;
9610 else
9611 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9612 }
9613
Alexis Huntc88db062010-01-13 09:01:02 +00009614 return false;
9615}
9616
Douglas Gregor07665a62009-01-05 19:45:36 +00009617/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9618/// linkage specification, including the language and (if present)
9619/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9620/// the location of the language string literal, which is provided
9621/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9622/// the '{' brace. Otherwise, this linkage specification does not
9623/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009624Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9625 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009626 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009627 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009628 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009629 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009630 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009631 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009632 Language = LinkageSpecDecl::lang_cxx;
9633 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009634 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009635 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009636 }
Mike Stump11289f42009-09-09 15:08:12 +00009637
Chris Lattner438e5012008-12-17 07:13:27 +00009638 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009639
Douglas Gregor07665a62009-01-05 19:45:36 +00009640 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009641 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009642 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009643 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009644 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009645}
9646
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009647/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009648/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9649/// valid, it's the position of the closing '}' brace in a linkage
9650/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009651Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009652 Decl *LinkageSpec,
9653 SourceLocation RBraceLoc) {
9654 if (LinkageSpec) {
9655 if (RBraceLoc.isValid()) {
9656 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9657 LSDecl->setRBraceLoc(RBraceLoc);
9658 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009659 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009660 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009661 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009662}
9663
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009664/// \brief Perform semantic analysis for the variable declaration that
9665/// occurs within a C++ catch clause, returning the newly-created
9666/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009667VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009668 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009669 SourceLocation StartLoc,
9670 SourceLocation Loc,
9671 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009672 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009673 QualType ExDeclType = TInfo->getType();
9674
Sebastian Redl54c04d42008-12-22 19:15:10 +00009675 // Arrays and functions decay.
9676 if (ExDeclType->isArrayType())
9677 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9678 else if (ExDeclType->isFunctionType())
9679 ExDeclType = Context.getPointerType(ExDeclType);
9680
9681 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9682 // The exception-declaration shall not denote a pointer or reference to an
9683 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009684 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009685 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009686 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009687 Invalid = true;
9688 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009689
Douglas Gregor104ee002010-03-08 01:47:36 +00009690 // GCC allows catching pointers and references to incomplete types
9691 // as an extension; so do we, but we warn by default.
9692
Sebastian Redl54c04d42008-12-22 19:15:10 +00009693 QualType BaseType = ExDeclType;
9694 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009695 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00009696 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009697 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009698 BaseType = Ptr->getPointeeType();
9699 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00009700 DK = diag::ext_catch_incomplete_ptr;
9701 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00009702 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009703 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009704 BaseType = Ref->getPointeeType();
9705 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00009706 DK = diag::ext_catch_incomplete_ref;
9707 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009708 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009709 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00009710 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9711 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00009712 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009713
Mike Stump11289f42009-09-09 15:08:12 +00009714 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009715 RequireNonAbstractType(Loc, ExDeclType,
9716 diag::err_abstract_type_in_decl,
9717 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009718 Invalid = true;
9719
John McCall2ca705e2010-07-24 00:37:23 +00009720 // Only the non-fragile NeXT runtime currently supports C++ catches
9721 // of ObjC types, and no runtime supports catching ObjC types by value.
9722 if (!Invalid && getLangOptions().ObjC1) {
9723 QualType T = ExDeclType;
9724 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9725 T = RT->getPointeeType();
9726
9727 if (T->isObjCObjectType()) {
9728 Diag(Loc, diag::err_objc_object_catch);
9729 Invalid = true;
9730 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009731 if (!getLangOptions().ObjCNonFragileABI)
9732 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009733 }
9734 }
9735
Abramo Bagnaradff19302011-03-08 08:55:46 +00009736 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9737 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009738 ExDecl->setExceptionVariable(true);
9739
Douglas Gregor750734c2011-07-06 18:14:43 +00009740 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009741 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009742 // C++ [except.handle]p16:
9743 // The object declared in an exception-declaration or, if the
9744 // exception-declaration does not specify a name, a temporary (12.2) is
9745 // copy-initialized (8.5) from the exception object. [...]
9746 // The object is destroyed when the handler exits, after the destruction
9747 // of any automatic objects initialized within the handler.
9748 //
9749 // We just pretend to initialize the object with itself, then make sure
9750 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009751 QualType initType = ExDeclType;
9752
9753 InitializedEntity entity =
9754 InitializedEntity::InitializeVariable(ExDecl);
9755 InitializationKind initKind =
9756 InitializationKind::CreateCopy(Loc, SourceLocation());
9757
9758 Expr *opaqueValue =
9759 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9760 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9761 ExprResult result = sequence.Perform(*this, entity, initKind,
9762 MultiExprArg(&opaqueValue, 1));
9763 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009764 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009765 else {
9766 // If the constructor used was non-trivial, set this as the
9767 // "initializer".
9768 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9769 if (!construct->getConstructor()->isTrivial()) {
9770 Expr *init = MaybeCreateExprWithCleanups(construct);
9771 ExDecl->setInit(init);
9772 }
9773
9774 // And make sure it's destructable.
9775 FinalizeVarWithDestructor(ExDecl, recordType);
9776 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009777 }
9778 }
9779
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009780 if (Invalid)
9781 ExDecl->setInvalidDecl();
9782
9783 return ExDecl;
9784}
9785
9786/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9787/// handler.
John McCall48871652010-08-21 09:40:31 +00009788Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009789 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009790 bool Invalid = D.isInvalidType();
9791
9792 // Check for unexpanded parameter packs.
9793 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9794 UPPC_ExceptionType)) {
9795 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9796 D.getIdentifierLoc());
9797 Invalid = true;
9798 }
9799
Sebastian Redl54c04d42008-12-22 19:15:10 +00009800 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009801 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009802 LookupOrdinaryName,
9803 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009804 // The scope should be freshly made just for us. There is just no way
9805 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009806 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009807 if (PrevDecl->isTemplateParameter()) {
9808 // Maybe we will complain about the shadowed template parameter.
9809 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009810 }
9811 }
9812
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009813 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009814 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9815 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009816 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009817 }
9818
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009819 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009820 D.getSourceRange().getBegin(),
9821 D.getIdentifierLoc(),
9822 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009823 if (Invalid)
9824 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009825
Sebastian Redl54c04d42008-12-22 19:15:10 +00009826 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009827 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009828 PushOnScopeChains(ExDecl, S);
9829 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009830 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009831
Douglas Gregor758a8692009-06-17 21:51:59 +00009832 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009833 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009834}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009835
Abramo Bagnaraea947882011-03-08 16:41:52 +00009836Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009837 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009838 Expr *AssertMessageExpr_,
9839 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009840 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009841
Anders Carlsson54b26982009-03-14 00:33:21 +00009842 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9843 llvm::APSInt Value(32);
9844 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009845 Diag(StaticAssertLoc,
9846 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00009847 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009848 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00009849 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009850
Anders Carlsson54b26982009-03-14 00:33:21 +00009851 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009852 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009853 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009854 }
9855 }
Mike Stump11289f42009-09-09 15:08:12 +00009856
Douglas Gregoref68fee2010-12-15 23:55:21 +00009857 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9858 return 0;
9859
Abramo Bagnaraea947882011-03-08 16:41:52 +00009860 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9861 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009862
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009863 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009864 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009865}
Sebastian Redlf769df52009-03-24 22:27:57 +00009866
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009867/// \brief Perform semantic analysis of the given friend type declaration.
9868///
9869/// \returns A friend declaration that.
9870FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9871 TypeSourceInfo *TSInfo) {
9872 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9873
9874 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009875 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009876
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009877 if (!getLangOptions().CPlusPlus0x) {
9878 // C++03 [class.friend]p2:
9879 // An elaborated-type-specifier shall be used in a friend declaration
9880 // for a class.*
9881 //
9882 // * The class-key of the elaborated-type-specifier is required.
9883 if (!ActiveTemplateInstantiations.empty()) {
9884 // Do not complain about the form of friend template types during
9885 // template instantiation; we will already have complained when the
9886 // template was declared.
9887 } else if (!T->isElaboratedTypeSpecifier()) {
9888 // If we evaluated the type to a record type, suggest putting
9889 // a tag in front.
9890 if (const RecordType *RT = T->getAs<RecordType>()) {
9891 RecordDecl *RD = RT->getDecl();
9892
9893 std::string InsertionText = std::string(" ") + RD->getKindName();
9894
9895 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9896 << (unsigned) RD->getTagKind()
9897 << T
9898 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9899 InsertionText);
9900 } else {
9901 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9902 << T
9903 << SourceRange(FriendLoc, TypeRange.getEnd());
9904 }
9905 } else if (T->getAs<EnumType>()) {
9906 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009907 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009908 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009909 }
9910 }
9911
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009912 // C++0x [class.friend]p3:
9913 // If the type specifier in a friend declaration designates a (possibly
9914 // cv-qualified) class type, that class is declared as a friend; otherwise,
9915 // the friend declaration is ignored.
9916
9917 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9918 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009919
9920 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9921}
9922
John McCallace48cd2010-10-19 01:40:49 +00009923/// Handle a friend tag declaration where the scope specifier was
9924/// templated.
9925Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9926 unsigned TagSpec, SourceLocation TagLoc,
9927 CXXScopeSpec &SS,
9928 IdentifierInfo *Name, SourceLocation NameLoc,
9929 AttributeList *Attr,
9930 MultiTemplateParamsArg TempParamLists) {
9931 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9932
9933 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00009934 bool Invalid = false;
9935
9936 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00009937 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00009938 TempParamLists.get(),
9939 TempParamLists.size(),
9940 /*friend*/ true,
9941 isExplicitSpecialization,
9942 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00009943 if (TemplateParams->size() > 0) {
9944 // This is a declaration of a class template.
9945 if (Invalid)
9946 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009947
Eric Christopher6f228b52011-07-21 05:34:24 +00009948 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9949 SS, Name, NameLoc, Attr,
9950 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +00009951 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +00009952 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009953 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00009954 } else {
9955 // The "template<>" header is extraneous.
9956 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9957 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9958 isExplicitSpecialization = true;
9959 }
9960 }
9961
9962 if (Invalid) return 0;
9963
9964 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9965
9966 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00009967 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00009968 if (TempParamLists.get()[I]->size()) {
9969 isAllExplicitSpecializations = false;
9970 break;
9971 }
9972 }
9973
9974 // FIXME: don't ignore attributes.
9975
9976 // If it's explicit specializations all the way down, just forget
9977 // about the template header and build an appropriate non-templated
9978 // friend. TODO: for source fidelity, remember the headers.
9979 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009980 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00009981 ElaboratedTypeKeyword Keyword
9982 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009983 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009984 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00009985 if (T.isNull())
9986 return 0;
9987
9988 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9989 if (isa<DependentNameType>(T)) {
9990 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9991 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009992 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009993 TL.setNameLoc(NameLoc);
9994 } else {
9995 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9996 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009997 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009998 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9999 }
10000
10001 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10002 TSI, FriendLoc);
10003 Friend->setAccess(AS_public);
10004 CurContext->addDecl(Friend);
10005 return Friend;
10006 }
10007
10008 // Handle the case of a templated-scope friend class. e.g.
10009 // template <class T> class A<T>::B;
10010 // FIXME: we don't support these right now.
10011 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10012 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10013 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10014 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10015 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010016 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000010017 TL.setNameLoc(NameLoc);
10018
10019 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10020 TSI, FriendLoc);
10021 Friend->setAccess(AS_public);
10022 Friend->setUnsupportedFriend(true);
10023 CurContext->addDecl(Friend);
10024 return Friend;
10025}
10026
10027
John McCall11083da2009-09-16 22:47:08 +000010028/// Handle a friend type declaration. This works in tandem with
10029/// ActOnTag.
10030///
10031/// Notes on friend class templates:
10032///
10033/// We generally treat friend class declarations as if they were
10034/// declaring a class. So, for example, the elaborated type specifier
10035/// in a friend declaration is required to obey the restrictions of a
10036/// class-head (i.e. no typedefs in the scope chain), template
10037/// parameters are required to match up with simple template-ids, &c.
10038/// However, unlike when declaring a template specialization, it's
10039/// okay to refer to a template specialization without an empty
10040/// template parameter declaration, e.g.
10041/// friend class A<T>::B<unsigned>;
10042/// We permit this as a special case; if there are any template
10043/// parameters present at all, require proper matching, i.e.
10044/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000010045Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000010046 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010047 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +000010048
10049 assert(DS.isFriendSpecified());
10050 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10051
John McCall11083da2009-09-16 22:47:08 +000010052 // Try to convert the decl specifier to a type. This works for
10053 // friend templates because ActOnTag never produces a ClassTemplateDecl
10054 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000010055 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000010056 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10057 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000010058 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000010059 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010060
Douglas Gregor6c110f32010-12-16 01:14:37 +000010061 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10062 return 0;
10063
John McCall11083da2009-09-16 22:47:08 +000010064 // This is definitely an error in C++98. It's probably meant to
10065 // be forbidden in C++0x, too, but the specification is just
10066 // poorly written.
10067 //
10068 // The problem is with declarations like the following:
10069 // template <T> friend A<T>::foo;
10070 // where deciding whether a class C is a friend or not now hinges
10071 // on whether there exists an instantiation of A that causes
10072 // 'foo' to equal C. There are restrictions on class-heads
10073 // (which we declare (by fiat) elaborated friend declarations to
10074 // be) that makes this tractable.
10075 //
10076 // FIXME: handle "template <> friend class A<T>;", which
10077 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000010078 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000010079 Diag(Loc, diag::err_tagless_friend_type_template)
10080 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010081 return 0;
John McCall11083da2009-09-16 22:47:08 +000010082 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010083
John McCallaa74a0c2009-08-28 07:59:38 +000010084 // C++98 [class.friend]p1: A friend of a class is a function
10085 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000010086 // This is fixed in DR77, which just barely didn't make the C++03
10087 // deadline. It's also a very silly restriction that seriously
10088 // affects inner classes and which nobody else seems to implement;
10089 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000010090 //
10091 // But note that we could warn about it: it's always useless to
10092 // friend one of your own members (it's not, however, worthless to
10093 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000010094
John McCall11083da2009-09-16 22:47:08 +000010095 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010096 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000010097 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010098 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +000010099 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +000010100 TSI,
John McCall11083da2009-09-16 22:47:08 +000010101 DS.getFriendSpecLoc());
10102 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010103 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
10104
10105 if (!D)
John McCall48871652010-08-21 09:40:31 +000010106 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010107
John McCall11083da2009-09-16 22:47:08 +000010108 D->setAccess(AS_public);
10109 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000010110
John McCall48871652010-08-21 09:40:31 +000010111 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000010112}
10113
John McCallde3fd222010-10-12 23:13:28 +000010114Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
10115 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010116 const DeclSpec &DS = D.getDeclSpec();
10117
10118 assert(DS.isFriendSpecified());
10119 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10120
10121 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000010122 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10123 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +000010124
10125 // C++ [class.friend]p1
10126 // A friend of a class is a function or class....
10127 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000010128 // It *doesn't* see through dependent types, which is correct
10129 // according to [temp.arg.type]p3:
10130 // If a declaration acquires a function type through a
10131 // type dependent on a template-parameter and this causes
10132 // a declaration that does not use the syntactic form of a
10133 // function declarator to have a function type, the program
10134 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +000010135 if (!T->isFunctionType()) {
10136 Diag(Loc, diag::err_unexpected_friend);
10137
10138 // It might be worthwhile to try to recover by creating an
10139 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000010140 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010141 }
10142
10143 // C++ [namespace.memdef]p3
10144 // - If a friend declaration in a non-local class first declares a
10145 // class or function, the friend class or function is a member
10146 // of the innermost enclosing namespace.
10147 // - The name of the friend is not found by simple name lookup
10148 // until a matching declaration is provided in that namespace
10149 // scope (either before or after the class declaration granting
10150 // friendship).
10151 // - If a friend function is called, its name may be found by the
10152 // name lookup that considers functions from namespaces and
10153 // classes associated with the types of the function arguments.
10154 // - When looking for a prior declaration of a class or a function
10155 // declared as a friend, scopes outside the innermost enclosing
10156 // namespace scope are not considered.
10157
John McCallde3fd222010-10-12 23:13:28 +000010158 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010159 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10160 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000010161 assert(Name);
10162
Douglas Gregor6c110f32010-12-16 01:14:37 +000010163 // Check for unexpanded parameter packs.
10164 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10165 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10166 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10167 return 0;
10168
John McCall07e91c02009-08-06 02:15:43 +000010169 // The context we found the declaration in, or in which we should
10170 // create the declaration.
10171 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000010172 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010173 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000010174 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000010175
John McCallde3fd222010-10-12 23:13:28 +000010176 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +000010177
John McCallde3fd222010-10-12 23:13:28 +000010178 // There are four cases here.
10179 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +000010180 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +000010181 // there as appropriate.
10182 // Recover from invalid scope qualifiers as if they just weren't there.
10183 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +000010184 // C++0x [namespace.memdef]p3:
10185 // If the name in a friend declaration is neither qualified nor
10186 // a template-id and the declaration is a function or an
10187 // elaborated-type-specifier, the lookup to determine whether
10188 // the entity has been previously declared shall not consider
10189 // any scopes outside the innermost enclosing namespace.
10190 // C++0x [class.friend]p11:
10191 // If a friend declaration appears in a local class and the name
10192 // specified is an unqualified name, a prior declaration is
10193 // looked up without considering scopes that are outside the
10194 // innermost enclosing non-class scope. For a friend function
10195 // declaration, if there is no prior declaration, the program is
10196 // ill-formed.
10197 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +000010198 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000010199
John McCallf7cfb222010-10-13 05:45:15 +000010200 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000010201 DC = CurContext;
10202 while (true) {
10203 // Skip class contexts. If someone can cite chapter and verse
10204 // for this behavior, that would be nice --- it's what GCC and
10205 // EDG do, and it seems like a reasonable intent, but the spec
10206 // really only says that checks for unqualified existing
10207 // declarations should stop at the nearest enclosing namespace,
10208 // not that they should only consider the nearest enclosing
10209 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010210 while (DC->isRecord())
10211 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000010212
John McCall1f82f242009-11-18 22:49:29 +000010213 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +000010214
10215 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +000010216 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +000010217 break;
John McCallf7cfb222010-10-13 05:45:15 +000010218
John McCallf4776592010-10-14 22:22:28 +000010219 if (isTemplateId) {
10220 if (isa<TranslationUnitDecl>(DC)) break;
10221 } else {
10222 if (DC->isFileContext()) break;
10223 }
John McCall07e91c02009-08-06 02:15:43 +000010224 DC = DC->getParent();
10225 }
10226
10227 // C++ [class.friend]p1: A friend of a class is a function or
10228 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +000010229 // C++0x changes this for both friend types and functions.
10230 // Most C++ 98 compilers do seem to give an error here, so
10231 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +000010232 if (!Previous.empty() && DC->Equals(CurContext)
10233 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +000010234 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +000010235
John McCallccbc0322010-10-13 06:22:15 +000010236 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +000010237
Douglas Gregor16e65612011-10-10 01:11:59 +000010238 // C++ [class.friend]p6:
10239 // A function can be defined in a friend declaration of a class if and
10240 // only if the class is a non-local class (9.8), the function name is
10241 // unqualified, and the function has namespace scope.
10242 if (isLocal && IsDefinition) {
10243 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10244 }
10245
John McCallde3fd222010-10-12 23:13:28 +000010246 // - There's a non-dependent scope specifier, in which case we
10247 // compute it and do a previous lookup there for a function
10248 // or function template.
10249 } else if (!SS.getScopeRep()->isDependent()) {
10250 DC = computeDeclContext(SS);
10251 if (!DC) return 0;
10252
10253 if (RequireCompleteDeclContext(SS, DC)) return 0;
10254
10255 LookupQualifiedName(Previous, DC);
10256
10257 // Ignore things found implicitly in the wrong scope.
10258 // TODO: better diagnostics for this case. Suggesting the right
10259 // qualified scope would be nice...
10260 LookupResult::Filter F = Previous.makeFilter();
10261 while (F.hasNext()) {
10262 NamedDecl *D = F.next();
10263 if (!DC->InEnclosingNamespaceSetOf(
10264 D->getDeclContext()->getRedeclContext()))
10265 F.erase();
10266 }
10267 F.done();
10268
10269 if (Previous.empty()) {
10270 D.setInvalidType();
10271 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
10272 return 0;
10273 }
10274
10275 // C++ [class.friend]p1: A friend of a class is a function or
10276 // class that is not a member of the class . . .
10277 if (DC->Equals(CurContext))
10278 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000010279
10280 if (IsDefinition) {
10281 // C++ [class.friend]p6:
10282 // A function can be defined in a friend declaration of a class if and
10283 // only if the class is a non-local class (9.8), the function name is
10284 // unqualified, and the function has namespace scope.
10285 SemaDiagnosticBuilder DB
10286 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10287
10288 DB << SS.getScopeRep();
10289 if (DC->isFileContext())
10290 DB << FixItHint::CreateRemoval(SS.getRange());
10291 SS.clear();
10292 }
John McCallde3fd222010-10-12 23:13:28 +000010293
10294 // - There's a scope specifier that does not match any template
10295 // parameter lists, in which case we use some arbitrary context,
10296 // create a method or method template, and wait for instantiation.
10297 // - There's a scope specifier that does match some template
10298 // parameter lists, which we don't handle right now.
10299 } else {
Douglas Gregor16e65612011-10-10 01:11:59 +000010300 if (IsDefinition) {
10301 // C++ [class.friend]p6:
10302 // A function can be defined in a friend declaration of a class if and
10303 // only if the class is a non-local class (9.8), the function name is
10304 // unqualified, and the function has namespace scope.
10305 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10306 << SS.getScopeRep();
10307 }
10308
John McCallde3fd222010-10-12 23:13:28 +000010309 DC = CurContext;
10310 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000010311 }
Douglas Gregor16e65612011-10-10 01:11:59 +000010312
John McCallf7cfb222010-10-13 05:45:15 +000010313 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000010314 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000010315 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10316 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10317 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000010318 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000010319 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10320 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000010321 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010322 }
John McCall07e91c02009-08-06 02:15:43 +000010323 }
Douglas Gregor16e65612011-10-10 01:11:59 +000010324
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010325 bool Redeclaration = false;
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010326 bool AddToScope = true;
John McCallccbc0322010-10-13 06:22:15 +000010327 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +000010328 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +000010329 IsDefinition,
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010330 Redeclaration, AddToScope);
John McCall48871652010-08-21 09:40:31 +000010331 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000010332
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010333 assert(ND->getDeclContext() == DC);
10334 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000010335
John McCall759e32b2009-08-31 22:39:49 +000010336 // Add the function declaration to the appropriate lookup tables,
10337 // adjusting the redeclarations list as necessary. We don't
10338 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000010339 //
John McCall759e32b2009-08-31 22:39:49 +000010340 // Also update the scope-based lookup if the target context's
10341 // lookup context is in lexical scope.
10342 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010343 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010344 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010345 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010346 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010347 }
John McCallaa74a0c2009-08-28 07:59:38 +000010348
10349 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010350 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000010351 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000010352 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000010353 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000010354
John McCallde3fd222010-10-12 23:13:28 +000010355 if (ND->isInvalidDecl())
10356 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +000010357 else {
10358 FunctionDecl *FD;
10359 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10360 FD = FTD->getTemplatedDecl();
10361 else
10362 FD = cast<FunctionDecl>(ND);
10363
10364 // Mark templated-scope function declarations as unsupported.
10365 if (FD->getNumTemplateParameterLists())
10366 FrD->setUnsupportedFriend(true);
10367 }
John McCallde3fd222010-10-12 23:13:28 +000010368
John McCall48871652010-08-21 09:40:31 +000010369 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000010370}
10371
John McCall48871652010-08-21 09:40:31 +000010372void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10373 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000010374
Sebastian Redlf769df52009-03-24 22:27:57 +000010375 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10376 if (!Fn) {
10377 Diag(DelLoc, diag::err_deleted_non_function);
10378 return;
10379 }
10380 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
10381 Diag(DelLoc, diag::err_deleted_decl_not_first);
10382 Diag(Prev->getLocation(), diag::note_previous_declaration);
10383 // If the declaration wasn't the first, we delete the function anyway for
10384 // recovery.
10385 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010386 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000010387}
Sebastian Redl4c018662009-04-27 21:33:24 +000010388
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010389void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10390 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10391
10392 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000010393 if (MD->getParent()->isDependentType()) {
10394 MD->setDefaulted();
10395 MD->setExplicitlyDefaulted();
10396 return;
10397 }
10398
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010399 CXXSpecialMember Member = getSpecialMember(MD);
10400 if (Member == CXXInvalid) {
10401 Diag(DefaultLoc, diag::err_default_special_members);
10402 return;
10403 }
10404
10405 MD->setDefaulted();
10406 MD->setExplicitlyDefaulted();
10407
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010408 // If this definition appears within the record, do the checking when
10409 // the record is complete.
10410 const FunctionDecl *Primary = MD;
10411 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10412 // Find the uninstantiated declaration that actually had the '= default'
10413 // on it.
10414 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10415
10416 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010417 return;
10418
10419 switch (Member) {
10420 case CXXDefaultConstructor: {
10421 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10422 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010423 if (!CD->isInvalidDecl())
10424 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10425 break;
10426 }
10427
10428 case CXXCopyConstructor: {
10429 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10430 CheckExplicitlyDefaultedCopyConstructor(CD);
10431 if (!CD->isInvalidDecl())
10432 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010433 break;
10434 }
Alexis Huntf91729462011-05-12 22:46:25 +000010435
Alexis Huntc9a55732011-05-14 05:23:28 +000010436 case CXXCopyAssignment: {
10437 CheckExplicitlyDefaultedCopyAssignment(MD);
10438 if (!MD->isInvalidDecl())
10439 DefineImplicitCopyAssignment(DefaultLoc, MD);
10440 break;
10441 }
10442
Alexis Huntf91729462011-05-12 22:46:25 +000010443 case CXXDestructor: {
10444 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10445 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010446 if (!DD->isInvalidDecl())
10447 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000010448 break;
10449 }
10450
Sebastian Redl22653ba2011-08-30 19:58:05 +000010451 case CXXMoveConstructor: {
10452 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10453 CheckExplicitlyDefaultedMoveConstructor(CD);
10454 if (!CD->isInvalidDecl())
10455 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000010456 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010457 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000010458
Sebastian Redl22653ba2011-08-30 19:58:05 +000010459 case CXXMoveAssignment: {
10460 CheckExplicitlyDefaultedMoveAssignment(MD);
10461 if (!MD->isInvalidDecl())
10462 DefineImplicitMoveAssignment(DefaultLoc, MD);
10463 break;
10464 }
10465
10466 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000010467 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010468 }
10469 } else {
10470 Diag(DefaultLoc, diag::err_default_special_members);
10471 }
10472}
10473
Sebastian Redl4c018662009-04-27 21:33:24 +000010474static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000010475 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000010476 Stmt *SubStmt = *CI;
10477 if (!SubStmt)
10478 continue;
10479 if (isa<ReturnStmt>(SubStmt))
10480 Self.Diag(SubStmt->getSourceRange().getBegin(),
10481 diag::err_return_in_constructor_handler);
10482 if (!isa<Expr>(SubStmt))
10483 SearchForReturnInStmt(Self, SubStmt);
10484 }
10485}
10486
10487void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10488 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10489 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10490 SearchForReturnInStmt(*this, Handler);
10491 }
10492}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010493
Mike Stump11289f42009-09-09 15:08:12 +000010494bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010495 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010496 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10497 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010498
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010499 if (Context.hasSameType(NewTy, OldTy) ||
10500 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010501 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010502
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010503 // Check if the return types are covariant
10504 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010505
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010506 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010507 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10508 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010509 NewClassTy = NewPT->getPointeeType();
10510 OldClassTy = OldPT->getPointeeType();
10511 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010512 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10513 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10514 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10515 NewClassTy = NewRT->getPointeeType();
10516 OldClassTy = OldRT->getPointeeType();
10517 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010518 }
10519 }
Mike Stump11289f42009-09-09 15:08:12 +000010520
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010521 // The return types aren't either both pointers or references to a class type.
10522 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010523 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010524 diag::err_different_return_type_for_overriding_virtual_function)
10525 << New->getDeclName() << NewTy << OldTy;
10526 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010527
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010528 return true;
10529 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010530
Anders Carlssone60365b2009-12-31 18:34:24 +000010531 // C++ [class.virtual]p6:
10532 // If the return type of D::f differs from the return type of B::f, the
10533 // class type in the return type of D::f shall be complete at the point of
10534 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010535 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10536 if (!RT->isBeingDefined() &&
10537 RequireCompleteType(New->getLocation(), NewClassTy,
10538 PDiag(diag::err_covariant_return_incomplete)
10539 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010540 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010541 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010542
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010543 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010544 // Check if the new class derives from the old class.
10545 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10546 Diag(New->getLocation(),
10547 diag::err_covariant_return_not_derived)
10548 << New->getDeclName() << NewTy << OldTy;
10549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10550 return true;
10551 }
Mike Stump11289f42009-09-09 15:08:12 +000010552
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010553 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010554 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010555 diag::err_covariant_return_inaccessible_base,
10556 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10557 // FIXME: Should this point to the return type?
10558 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010559 // FIXME: this note won't trigger for delayed access control
10560 // diagnostics, and it's impossible to get an undelayed error
10561 // here from access control during the original parse because
10562 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010563 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10564 return true;
10565 }
10566 }
Mike Stump11289f42009-09-09 15:08:12 +000010567
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010568 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010569 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010570 Diag(New->getLocation(),
10571 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010572 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010573 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10574 return true;
10575 };
Mike Stump11289f42009-09-09 15:08:12 +000010576
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010577
10578 // The new class type must have the same or less qualifiers as the old type.
10579 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10580 Diag(New->getLocation(),
10581 diag::err_covariant_return_type_class_type_more_qualified)
10582 << New->getDeclName() << NewTy << OldTy;
10583 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10584 return true;
10585 };
Mike Stump11289f42009-09-09 15:08:12 +000010586
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010587 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010588}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010589
Douglas Gregor21920e372009-12-01 17:24:26 +000010590/// \brief Mark the given method pure.
10591///
10592/// \param Method the method to be marked pure.
10593///
10594/// \param InitRange the source range that covers the "0" initializer.
10595bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010596 SourceLocation EndLoc = InitRange.getEnd();
10597 if (EndLoc.isValid())
10598 Method->setRangeEnd(EndLoc);
10599
Douglas Gregor21920e372009-12-01 17:24:26 +000010600 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10601 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010602 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010603 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010604
10605 if (!Method->isInvalidDecl())
10606 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10607 << Method->getDeclName() << InitRange;
10608 return true;
10609}
10610
John McCall1f4ee7b2009-12-19 09:28:58 +000010611/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10612/// an initializer for the out-of-line declaration 'Dcl'. The scope
10613/// is a fresh scope pushed for just this purpose.
10614///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010615/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10616/// static data member of class X, names should be looked up in the scope of
10617/// class X.
John McCall48871652010-08-21 09:40:31 +000010618void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010619 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010620 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010621
John McCall1f4ee7b2009-12-19 09:28:58 +000010622 // We should only get called for declarations with scope specifiers, like:
10623 // int foo::bar;
10624 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010625 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010626}
10627
10628/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010629/// initializer for the out-of-line declaration 'D'.
10630void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010631 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010632 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010633
John McCall1f4ee7b2009-12-19 09:28:58 +000010634 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010635 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010636}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010637
10638/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10639/// C++ if/switch/while/for statement.
10640/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010641DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010642 // C++ 6.4p2:
10643 // The declarator shall not specify a function or an array.
10644 // The type-specifier-seq shall not contain typedef and shall not declare a
10645 // new class or enumeration.
10646 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10647 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010648
10649 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010650 if (!Dcl)
10651 return true;
10652
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010653 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10654 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010655 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010656 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010657 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010658
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010659 return Dcl;
10660}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010661
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010662void Sema::LoadExternalVTableUses() {
10663 if (!ExternalSource)
10664 return;
10665
10666 SmallVector<ExternalVTableUse, 4> VTables;
10667 ExternalSource->ReadUsedVTables(VTables);
10668 SmallVector<VTableUse, 4> NewUses;
10669 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10670 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10671 = VTablesUsed.find(VTables[I].Record);
10672 // Even if a definition wasn't required before, it may be required now.
10673 if (Pos != VTablesUsed.end()) {
10674 if (!Pos->second && VTables[I].DefinitionRequired)
10675 Pos->second = true;
10676 continue;
10677 }
10678
10679 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10680 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10681 }
10682
10683 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10684}
10685
Douglas Gregor88d292c2010-05-13 16:44:06 +000010686void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10687 bool DefinitionRequired) {
10688 // Ignore any vtable uses in unevaluated operands or for classes that do
10689 // not have a vtable.
10690 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10691 CurContext->isDependentContext() ||
10692 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010693 return;
10694
Douglas Gregor88d292c2010-05-13 16:44:06 +000010695 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010696 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010697 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10698 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10699 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10700 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010701 // If we already had an entry, check to see if we are promoting this vtable
10702 // to required a definition. If so, we need to reappend to the VTableUses
10703 // list, since we may have already processed the first entry.
10704 if (DefinitionRequired && !Pos.first->second) {
10705 Pos.first->second = true;
10706 } else {
10707 // Otherwise, we can early exit.
10708 return;
10709 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010710 }
10711
10712 // Local classes need to have their virtual members marked
10713 // immediately. For all other classes, we mark their virtual members
10714 // at the end of the translation unit.
10715 if (Class->isLocalClass())
10716 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010717 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010718 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010719}
10720
Douglas Gregor88d292c2010-05-13 16:44:06 +000010721bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010722 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010723 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010724 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010725
Douglas Gregor88d292c2010-05-13 16:44:06 +000010726 // Note: The VTableUses vector could grow as a result of marking
10727 // the members of a class as "used", so we check the size each
10728 // time through the loop and prefer indices (with are stable) to
10729 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010730 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010731 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010732 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010733 if (!Class)
10734 continue;
10735
10736 SourceLocation Loc = VTableUses[I].second;
10737
10738 // If this class has a key function, but that key function is
10739 // defined in another translation unit, we don't need to emit the
10740 // vtable even though we're using it.
10741 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010742 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010743 switch (KeyFunction->getTemplateSpecializationKind()) {
10744 case TSK_Undeclared:
10745 case TSK_ExplicitSpecialization:
10746 case TSK_ExplicitInstantiationDeclaration:
10747 // The key function is in another translation unit.
10748 continue;
10749
10750 case TSK_ExplicitInstantiationDefinition:
10751 case TSK_ImplicitInstantiation:
10752 // We will be instantiating the key function.
10753 break;
10754 }
10755 } else if (!KeyFunction) {
10756 // If we have a class with no key function that is the subject
10757 // of an explicit instantiation declaration, suppress the
10758 // vtable; it will live with the explicit instantiation
10759 // definition.
10760 bool IsExplicitInstantiationDeclaration
10761 = Class->getTemplateSpecializationKind()
10762 == TSK_ExplicitInstantiationDeclaration;
10763 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10764 REnd = Class->redecls_end();
10765 R != REnd; ++R) {
10766 TemplateSpecializationKind TSK
10767 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10768 if (TSK == TSK_ExplicitInstantiationDeclaration)
10769 IsExplicitInstantiationDeclaration = true;
10770 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10771 IsExplicitInstantiationDeclaration = false;
10772 break;
10773 }
10774 }
10775
10776 if (IsExplicitInstantiationDeclaration)
10777 continue;
10778 }
10779
10780 // Mark all of the virtual members of this class as referenced, so
10781 // that we can build a vtable. Then, tell the AST consumer that a
10782 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010783 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010784 MarkVirtualMembersReferenced(Loc, Class);
10785 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10786 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10787
10788 // Optionally warn if we're emitting a weak vtable.
10789 if (Class->getLinkage() == ExternalLinkage &&
10790 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010791 const FunctionDecl *KeyFunctionDef = 0;
10792 if (!KeyFunction ||
10793 (KeyFunction->hasBody(KeyFunctionDef) &&
10794 KeyFunctionDef->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +000010795 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10796 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010797 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010798 VTableUses.clear();
10799
Douglas Gregor97509692011-04-22 22:25:37 +000010800 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010801}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010802
Rafael Espindola5b334082010-03-26 00:36:59 +000010803void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10804 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010805 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10806 e = RD->method_end(); i != e; ++i) {
10807 CXXMethodDecl *MD = *i;
10808
10809 // C++ [basic.def.odr]p2:
10810 // [...] A virtual member function is used if it is not pure. [...]
10811 if (MD->isVirtual() && !MD->isPure())
10812 MarkDeclarationReferenced(Loc, MD);
10813 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010814
10815 // Only classes that have virtual bases need a VTT.
10816 if (RD->getNumVBases() == 0)
10817 return;
10818
10819 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10820 e = RD->bases_end(); i != e; ++i) {
10821 const CXXRecordDecl *Base =
10822 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010823 if (Base->getNumVBases() == 0)
10824 continue;
10825 MarkVirtualMembersReferenced(Loc, Base);
10826 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010827}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010828
10829/// SetIvarInitializers - This routine builds initialization ASTs for the
10830/// Objective-C implementation whose ivars need be initialized.
10831void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10832 if (!getLangOptions().CPlusPlus)
10833 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010834 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010835 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010836 CollectIvarsToConstructOrDestruct(OID, ivars);
10837 if (ivars.empty())
10838 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010839 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010840 for (unsigned i = 0; i < ivars.size(); i++) {
10841 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010842 if (Field->isInvalidDecl())
10843 continue;
10844
Alexis Hunt1d792652011-01-08 20:30:50 +000010845 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010846 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10847 InitializationKind InitKind =
10848 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10849
10850 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010851 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010852 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010853 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010854 // Note, MemberInit could actually come back empty if no initialization
10855 // is required (e.g., because it would call a trivial default constructor)
10856 if (!MemberInit.get() || MemberInit.isInvalid())
10857 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010858
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010859 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010860 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10861 SourceLocation(),
10862 MemberInit.takeAs<Expr>(),
10863 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010864 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010865
10866 // Be sure that the destructor is accessible and is marked as referenced.
10867 if (const RecordType *RecordTy
10868 = Context.getBaseElementType(Field->getType())
10869 ->getAs<RecordType>()) {
10870 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010871 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +000010872 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10873 CheckDestructorAccess(Field->getLocation(), Destructor,
10874 PDiag(diag::err_access_dtor_ivar)
10875 << Context.getBaseElementType(Field->getType()));
10876 }
10877 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010878 }
10879 ObjCImplementation->setIvarInitializers(Context,
10880 AllToInit.data(), AllToInit.size());
10881 }
10882}
Alexis Hunt6118d662011-05-04 05:57:24 +000010883
Alexis Hunt27a761d2011-05-04 23:29:54 +000010884static
10885void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10886 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10887 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10888 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10889 Sema &S) {
10890 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10891 CE = Current.end();
10892 if (Ctor->isInvalidDecl())
10893 return;
10894
10895 const FunctionDecl *FNTarget = 0;
10896 CXXConstructorDecl *Target;
10897
10898 // We ignore the result here since if we don't have a body, Target will be
10899 // null below.
10900 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10901 Target
10902= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10903
10904 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10905 // Avoid dereferencing a null pointer here.
10906 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10907
10908 if (!Current.insert(Canonical))
10909 return;
10910
10911 // We know that beyond here, we aren't chaining into a cycle.
10912 if (!Target || !Target->isDelegatingConstructor() ||
10913 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10914 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10915 Valid.insert(*CI);
10916 Current.clear();
10917 // We've hit a cycle.
10918 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10919 Current.count(TCanonical)) {
10920 // If we haven't diagnosed this cycle yet, do so now.
10921 if (!Invalid.count(TCanonical)) {
10922 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000010923 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000010924 << Ctor;
10925
10926 // Don't add a note for a function delegating directo to itself.
10927 if (TCanonical != Canonical)
10928 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10929
10930 CXXConstructorDecl *C = Target;
10931 while (C->getCanonicalDecl() != Canonical) {
10932 (void)C->getTargetConstructor()->hasBody(FNTarget);
10933 assert(FNTarget && "Ctor cycle through bodiless function");
10934
10935 C
10936 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10937 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10938 }
10939 }
10940
10941 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10942 Invalid.insert(*CI);
10943 Current.clear();
10944 } else {
10945 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10946 }
10947}
10948
10949
Alexis Hunt6118d662011-05-04 05:57:24 +000010950void Sema::CheckDelegatingCtorCycles() {
10951 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10952
Alexis Hunt27a761d2011-05-04 23:29:54 +000010953 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10954 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000010955
Douglas Gregorbae31202011-07-27 21:57:17 +000010956 for (DelegatingCtorDeclsType::iterator
10957 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000010958 E = DelegatingCtorDecls.end();
10959 I != E; ++I) {
10960 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000010961 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000010962
10963 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10964 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000010965}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010966
10967/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10968Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10969 // Implicitly declared functions (e.g. copy constructors) are
10970 // __host__ __device__
10971 if (D->isImplicit())
10972 return CFT_HostDevice;
10973
10974 if (D->hasAttr<CUDAGlobalAttr>())
10975 return CFT_Global;
10976
10977 if (D->hasAttr<CUDADeviceAttr>()) {
10978 if (D->hasAttr<CUDAHostAttr>())
10979 return CFT_HostDevice;
10980 else
10981 return CFT_Device;
10982 }
10983
10984 return CFT_Host;
10985}
10986
10987bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10988 CUDAFunctionTarget CalleeTarget) {
10989 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10990 // Callable from the device only."
10991 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10992 return true;
10993
10994 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10995 // Callable from the host only."
10996 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10997 // Callable from the host only."
10998 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10999 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11000 return true;
11001
11002 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11003 return true;
11004
11005 return false;
11006}