blob: 031afa078dac57f0461409ca253e5666527c6658 [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 }
905 } else if (!Constructor->isDelegatingConstructor()) {
906 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
907
908 // Skip detailed checking if we have enough initializers, and we would
909 // allow at most one initializer per member.
910 bool AnyAnonStructUnionMembers = false;
911 unsigned Fields = 0;
912 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
913 E = RD->field_end(); I != E; ++I, ++Fields) {
914 if ((*I)->isAnonymousStructOrUnion()) {
915 AnyAnonStructUnionMembers = true;
916 break;
917 }
918 }
919 if (AnyAnonStructUnionMembers ||
920 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
921 // Check initialization of non-static data members. Base classes are
922 // always initialized so do not need to be checked. Dependent bases
923 // might not have initializers in the member initializer list.
924 llvm::SmallSet<Decl*, 16> Inits;
925 for (CXXConstructorDecl::init_const_iterator
926 I = Constructor->init_begin(), E = Constructor->init_end();
927 I != E; ++I) {
928 if (FieldDecl *FD = (*I)->getMember())
929 Inits.insert(FD);
930 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
931 Inits.insert(ID->chain_begin(), ID->chain_end());
932 }
933
934 bool Diagnosed = false;
935 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
936 E = RD->field_end(); I != E; ++I)
937 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
938 if (Diagnosed)
939 return false;
940 }
941 }
942
943 // FIXME
944 // - every constructor involved in initializing non-static data members
945 // and base class sub-objects shall be a constexpr constructor;
946 // - every assignment-expression that is an initializer-clause appearing
947 // directly or indirectly within a brace-or-equal-initializer for
948 // a non-static data member that is not named by a mem-initializer-id
949 // shall be a constant expression; and
950 // - every implicit conversion used in converting a constructor argument
951 // to the corresponding parameter type and converting
952 // a full-expression to the corresponding member type shall be one of
953 // those allowed in a constant expression.
954 // Deal with these as part of a general check that the function can produce
955 // a constant expression (for [dcl.constexpr]p5).
956 } else {
957 if (ReturnStmts.empty()) {
958 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
959 return false;
960 }
961 if (ReturnStmts.size() > 1) {
962 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
963 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
964 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
965 return false;
966 }
967 }
968
969 return true;
970}
971
Douglas Gregor61956c42008-10-31 09:07:45 +0000972/// isCurrentClassName - Determine whether the identifier II is the
973/// name of the class type currently being defined. In the case of
974/// nested classes, this will only return true if II is the name of
975/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000976bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
977 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000978 assert(getLangOptions().CPlusPlus && "No class names in C!");
979
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000980 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000981 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000982 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000983 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
984 } else
985 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
986
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000987 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000988 return &II == CurDecl->getIdentifier();
989 else
990 return false;
991}
992
Mike Stump11289f42009-09-09 15:08:12 +0000993/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000994///
995/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
996/// and returns NULL otherwise.
997CXXBaseSpecifier *
998Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
999 SourceRange SpecifierRange,
1000 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001001 TypeSourceInfo *TInfo,
1002 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001003 QualType BaseType = TInfo->getType();
1004
Douglas Gregor463421d2009-03-03 04:44:36 +00001005 // C++ [class.union]p1:
1006 // A union shall not have base classes.
1007 if (Class->isUnion()) {
1008 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1009 << SpecifierRange;
1010 return 0;
1011 }
1012
Douglas Gregor752a5952011-01-03 22:36:02 +00001013 if (EllipsisLoc.isValid() &&
1014 !TInfo->getType()->containsUnexpandedParameterPack()) {
1015 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1016 << TInfo->getTypeLoc().getSourceRange();
1017 EllipsisLoc = SourceLocation();
1018 }
1019
Douglas Gregor463421d2009-03-03 04:44:36 +00001020 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +00001021 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001022 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001023 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001024
1025 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +00001026
1027 // Base specifiers must be record types.
1028 if (!BaseType->isRecordType()) {
1029 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1030 return 0;
1031 }
1032
1033 // C++ [class.union]p1:
1034 // A union shall not be used as a base class.
1035 if (BaseType->isUnionType()) {
1036 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1037 return 0;
1038 }
1039
1040 // C++ [class.derived]p2:
1041 // The class-name in a base-specifier shall not be an incompletely
1042 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001043 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00001044 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +00001045 << SpecifierRange)) {
1046 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001047 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001048 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001049
Eli Friedmanc96d4962009-08-15 21:55:26 +00001050 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001051 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001052 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001053 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001054 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +00001055 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1056 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001057
Anders Carlsson65c76d32011-03-25 14:55:14 +00001058 // C++ [class]p3:
1059 // If a class is marked final and it appears as a base-type-specifier in
1060 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001061 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001062 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1063 << CXXBaseDecl->getDeclName();
1064 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1065 << CXXBaseDecl->getDeclName();
1066 return 0;
1067 }
1068
John McCall3696dcb2010-08-17 07:23:57 +00001069 if (BaseDecl->isInvalidDecl())
1070 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001071
1072 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001073 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001074 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001075 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001076}
1077
Douglas Gregor556877c2008-04-13 21:30:24 +00001078/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1079/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001080/// example:
1081/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001082/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001083BaseResult
John McCall48871652010-08-21 09:40:31 +00001084Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +00001085 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001086 ParsedType basetype, SourceLocation BaseLoc,
1087 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001088 if (!classdecl)
1089 return true;
1090
Douglas Gregorc40290e2009-03-09 23:48:35 +00001091 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001092 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001093 if (!Class)
1094 return true;
1095
Nick Lewycky19b9f952010-07-26 16:56:01 +00001096 TypeSourceInfo *TInfo = 0;
1097 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001098
Douglas Gregor752a5952011-01-03 22:36:02 +00001099 if (EllipsisLoc.isInvalid() &&
1100 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001101 UPPC_BaseType))
1102 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001103
Douglas Gregor463421d2009-03-03 04:44:36 +00001104 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001105 Virtual, Access, TInfo,
1106 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001107 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +00001108
Douglas Gregor463421d2009-03-03 04:44:36 +00001109 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001110}
Douglas Gregor556877c2008-04-13 21:30:24 +00001111
Douglas Gregor463421d2009-03-03 04:44:36 +00001112/// \brief Performs the actual work of attaching the given base class
1113/// specifiers to a C++ class.
1114bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1115 unsigned NumBases) {
1116 if (NumBases == 0)
1117 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001118
1119 // Used to keep track of which base types we have already seen, so
1120 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001121 // that the key is always the unqualified canonical type of the base
1122 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001123 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1124
1125 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001126 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001127 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001128 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001129 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001130 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001131 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +00001132 if (KnownBaseTypes[NewBaseType]) {
1133 // C++ [class.mi]p3:
1134 // A class shall not be specified as a direct base class of a
1135 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +00001136 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001137 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001138 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001139 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001140
1141 // Delete the duplicate base class specifier; we're going to
1142 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001143 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001144
1145 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001146 } else {
1147 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +00001148 KnownBaseTypes[NewBaseType] = Bases[idx];
1149 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +00001150 }
1151 }
1152
1153 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001154 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001155
1156 // Delete the remaining (good) base class specifiers, since their
1157 // data has been copied into the CXXRecordDecl.
1158 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001159 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001160
1161 return Invalid;
1162}
1163
1164/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1165/// class, after checking whether there are any duplicate base
1166/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001167void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001168 unsigned NumBases) {
1169 if (!ClassDecl || !Bases || !NumBases)
1170 return;
1171
1172 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001173 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001174 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001175}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001176
John McCalle78aac42010-03-10 03:28:59 +00001177static CXXRecordDecl *GetClassForType(QualType T) {
1178 if (const RecordType *RT = T->getAs<RecordType>())
1179 return cast<CXXRecordDecl>(RT->getDecl());
1180 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1181 return ICT->getDecl();
1182 else
1183 return 0;
1184}
1185
Douglas Gregor36d1b142009-10-06 17:59:45 +00001186/// \brief Determine whether the type \p Derived is a C++ class that is
1187/// derived from the type \p Base.
1188bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1189 if (!getLangOptions().CPlusPlus)
1190 return false;
John McCalle78aac42010-03-10 03:28:59 +00001191
1192 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1193 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001194 return false;
1195
John McCalle78aac42010-03-10 03:28:59 +00001196 CXXRecordDecl *BaseRD = GetClassForType(Base);
1197 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001198 return false;
1199
John McCall67da35c2010-02-04 22:26:26 +00001200 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1201 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001202}
1203
1204/// \brief Determine whether the type \p Derived is a C++ class that is
1205/// derived from the type \p Base.
1206bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1207 if (!getLangOptions().CPlusPlus)
1208 return false;
1209
John McCalle78aac42010-03-10 03:28:59 +00001210 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1211 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001212 return false;
1213
John McCalle78aac42010-03-10 03:28:59 +00001214 CXXRecordDecl *BaseRD = GetClassForType(Base);
1215 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001216 return false;
1217
Douglas Gregor36d1b142009-10-06 17:59:45 +00001218 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1219}
1220
Anders Carlssona70cff62010-04-24 19:06:50 +00001221void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001222 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001223 assert(BasePathArray.empty() && "Base path array must be empty!");
1224 assert(Paths.isRecordingPaths() && "Must record paths!");
1225
1226 const CXXBasePath &Path = Paths.front();
1227
1228 // We first go backward and check if we have a virtual base.
1229 // FIXME: It would be better if CXXBasePath had the base specifier for
1230 // the nearest virtual base.
1231 unsigned Start = 0;
1232 for (unsigned I = Path.size(); I != 0; --I) {
1233 if (Path[I - 1].Base->isVirtual()) {
1234 Start = I - 1;
1235 break;
1236 }
1237 }
1238
1239 // Now add all bases.
1240 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001241 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001242}
1243
Douglas Gregor88d292c2010-05-13 16:44:06 +00001244/// \brief Determine whether the given base path includes a virtual
1245/// base class.
John McCallcf142162010-08-07 06:22:56 +00001246bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1247 for (CXXCastPath::const_iterator B = BasePath.begin(),
1248 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001249 B != BEnd; ++B)
1250 if ((*B)->isVirtual())
1251 return true;
1252
1253 return false;
1254}
1255
Douglas Gregor36d1b142009-10-06 17:59:45 +00001256/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1257/// conversion (where Derived and Base are class types) is
1258/// well-formed, meaning that the conversion is unambiguous (and
1259/// that all of the base classes are accessible). Returns true
1260/// and emits a diagnostic if the code is ill-formed, returns false
1261/// otherwise. Loc is the location where this routine should point to
1262/// if there is an error, and Range is the source range to highlight
1263/// if there is an error.
1264bool
1265Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001266 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001267 unsigned AmbigiousBaseConvID,
1268 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001269 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001270 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001271 // First, determine whether the path from Derived to Base is
1272 // ambiguous. This is slightly more expensive than checking whether
1273 // the Derived to Base conversion exists, because here we need to
1274 // explore multiple paths to determine if there is an ambiguity.
1275 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1276 /*DetectVirtual=*/false);
1277 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1278 assert(DerivationOkay &&
1279 "Can only be used with a derived-to-base conversion");
1280 (void)DerivationOkay;
1281
1282 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001283 if (InaccessibleBaseID) {
1284 // Check that the base class can be accessed.
1285 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1286 InaccessibleBaseID)) {
1287 case AR_inaccessible:
1288 return true;
1289 case AR_accessible:
1290 case AR_dependent:
1291 case AR_delayed:
1292 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001293 }
John McCall5b0829a2010-02-10 09:31:12 +00001294 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001295
1296 // Build a base path if necessary.
1297 if (BasePath)
1298 BuildBasePathArray(Paths, *BasePath);
1299 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001300 }
1301
1302 // We know that the derived-to-base conversion is ambiguous, and
1303 // we're going to produce a diagnostic. Perform the derived-to-base
1304 // search just one more time to compute all of the possible paths so
1305 // that we can print them out. This is more expensive than any of
1306 // the previous derived-to-base checks we've done, but at this point
1307 // performance isn't as much of an issue.
1308 Paths.clear();
1309 Paths.setRecordingPaths(true);
1310 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1311 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1312 (void)StillOkay;
1313
1314 // Build up a textual representation of the ambiguous paths, e.g.,
1315 // D -> B -> A, that will be used to illustrate the ambiguous
1316 // conversions in the diagnostic. We only print one of the paths
1317 // to each base class subobject.
1318 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1319
1320 Diag(Loc, AmbigiousBaseConvID)
1321 << Derived << Base << PathDisplayStr << Range << Name;
1322 return true;
1323}
1324
1325bool
1326Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001327 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001328 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001329 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001330 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001331 IgnoreAccess ? 0
1332 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001333 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001334 Loc, Range, DeclarationName(),
1335 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001336}
1337
1338
1339/// @brief Builds a string representing ambiguous paths from a
1340/// specific derived class to different subobjects of the same base
1341/// class.
1342///
1343/// This function builds a string that can be used in error messages
1344/// to show the different paths that one can take through the
1345/// inheritance hierarchy to go from the derived class to different
1346/// subobjects of a base class. The result looks something like this:
1347/// @code
1348/// struct D -> struct B -> struct A
1349/// struct D -> struct C -> struct A
1350/// @endcode
1351std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1352 std::string PathDisplayStr;
1353 std::set<unsigned> DisplayedPaths;
1354 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1355 Path != Paths.end(); ++Path) {
1356 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1357 // We haven't displayed a path to this particular base
1358 // class subobject yet.
1359 PathDisplayStr += "\n ";
1360 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1361 for (CXXBasePath::const_iterator Element = Path->begin();
1362 Element != Path->end(); ++Element)
1363 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1364 }
1365 }
1366
1367 return PathDisplayStr;
1368}
1369
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001370//===----------------------------------------------------------------------===//
1371// C++ class member Handling
1372//===----------------------------------------------------------------------===//
1373
Abramo Bagnarad7340582010-06-05 05:09:32 +00001374/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +00001375Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1376 SourceLocation ASLoc,
1377 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001378 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001379 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001380 ASLoc, ColonLoc);
1381 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +00001382 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +00001383}
1384
Anders Carlssonfd835532011-01-20 05:57:14 +00001385/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001386void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001387 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001388 if (!MD || !MD->isVirtual())
1389 return;
1390
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001391 if (MD->isDependentContext())
1392 return;
1393
Anders Carlssonfd835532011-01-20 05:57:14 +00001394 // C++0x [class.virtual]p3:
1395 // If a virtual function is marked with the virt-specifier override and does
1396 // not override a member function of a base class,
1397 // the program is ill-formed.
1398 bool HasOverriddenMethods =
1399 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001400 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001401 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001402 diag::err_function_marked_override_not_overriding)
1403 << MD->getDeclName();
1404 return;
1405 }
1406}
1407
Anders Carlsson3f610c72011-01-20 16:25:36 +00001408/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1409/// function overrides a virtual member function marked 'final', according to
1410/// C++0x [class.virtual]p3.
1411bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1412 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001413 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001414 return false;
1415
1416 Diag(New->getLocation(), diag::err_final_function_overridden)
1417 << New->getDeclName();
1418 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1419 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001420}
1421
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001422/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1423/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001424/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1425/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1426/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001427Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001428Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001429 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001430 Expr *BW, const VirtSpecifiers &VS,
1431 Expr *InitExpr, bool HasDeferredInit,
Richard Smith938f40b2011-06-11 17:19:42 +00001432 bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001433 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001434 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1435 DeclarationName Name = NameInfo.getName();
1436 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001437
1438 // For anonymous bitfields, the location should point to the type.
1439 if (Loc.isInvalid())
1440 Loc = D.getSourceRange().getBegin();
1441
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001442 Expr *BitWidth = static_cast<Expr*>(BW);
1443 Expr *Init = static_cast<Expr*>(InitExpr);
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());
Richard Smith938f40b2011-06-11 17:19:42 +00001447 assert(!Init || !HasDeferredInit);
John McCall07e91c02009-08-06 02:15:43 +00001448
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001449 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001450
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001451 // C++ 9.2p6: A member shall not be declared to have automatic storage
1452 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001453 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1454 // data members and cannot be applied to names declared const or static,
1455 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001456 switch (DS.getStorageClassSpec()) {
1457 case DeclSpec::SCS_unspecified:
1458 case DeclSpec::SCS_typedef:
1459 case DeclSpec::SCS_static:
1460 // FALL THROUGH.
1461 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001462 case DeclSpec::SCS_mutable:
1463 if (isFunc) {
1464 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001465 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001466 else
Chris Lattner3b054132008-11-19 05:08:23 +00001467 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001468
Sebastian Redl8071edb2008-11-17 23:24:37 +00001469 // FIXME: It would be nicer if the keyword was ignored only for this
1470 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001471 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001472 }
1473 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001474 default:
1475 if (DS.getStorageClassSpecLoc().isValid())
1476 Diag(DS.getStorageClassSpecLoc(),
1477 diag::err_storageclass_invalid_for_member);
1478 else
1479 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1480 D.getMutableDeclSpec().ClearStorageClassSpecs();
1481 }
1482
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001483 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1484 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001485 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001486
1487 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001488 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001489 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001490
1491 // Data members must have identifiers for names.
1492 if (Name.getNameKind() != DeclarationName::Identifier) {
1493 Diag(Loc, diag::err_bad_variable_name)
1494 << Name;
1495 return 0;
1496 }
Douglas Gregora007d362010-10-13 22:19:53 +00001497
Douglas Gregor7c26c042011-09-21 14:40:46 +00001498 IdentifierInfo *II = Name.getAsIdentifierInfo();
1499
1500 // Member field could not be with "template" keyword.
1501 // So TemplateParameterLists should be empty in this case.
1502 if (TemplateParameterLists.size()) {
1503 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1504 if (TemplateParams->size()) {
1505 // There is no such thing as a member field template.
1506 Diag(D.getIdentifierLoc(), diag::err_template_member)
1507 << II
1508 << SourceRange(TemplateParams->getTemplateLoc(),
1509 TemplateParams->getRAngleLoc());
1510 } else {
1511 // There is an extraneous 'template<>' for this member.
1512 Diag(TemplateParams->getTemplateLoc(),
1513 diag::err_template_member_noparams)
1514 << II
1515 << SourceRange(TemplateParams->getTemplateLoc(),
1516 TemplateParams->getRAngleLoc());
1517 }
1518 return 0;
1519 }
1520
Douglas Gregora007d362010-10-13 22:19:53 +00001521 if (SS.isSet() && !SS.isInvalid()) {
1522 // The user provided a superfluous scope specifier inside a class
1523 // definition:
1524 //
1525 // class X {
1526 // int X::member;
1527 // };
1528 DeclContext *DC = 0;
1529 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1530 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1531 << Name << FixItHint::CreateRemoval(SS.getRange());
1532 else
1533 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1534 << Name << SS.getRange();
1535
1536 SS.clear();
1537 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001538
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001539 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001540 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001541 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001542 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001543 assert(!HasDeferredInit);
1544
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001545 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001546 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001547 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001548 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001549
1550 // Non-instance-fields can't have a bitfield.
1551 if (BitWidth) {
1552 if (Member->isInvalidDecl()) {
1553 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001554 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001555 // C++ 9.6p3: A bit-field shall not be a static member.
1556 // "static member 'A' cannot be a bit-field"
1557 Diag(Loc, diag::err_static_not_bitfield)
1558 << Name << BitWidth->getSourceRange();
1559 } else if (isa<TypedefDecl>(Member)) {
1560 // "typedef member 'x' cannot be a bit-field"
1561 Diag(Loc, diag::err_typedef_not_bitfield)
1562 << Name << BitWidth->getSourceRange();
1563 } else {
1564 // A function typedef ("typedef int f(); f a;").
1565 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1566 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001567 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001568 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattnerd26760a2009-03-05 23:01:03 +00001571 BitWidth = 0;
1572 Member->setInvalidDecl();
1573 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001574
1575 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Douglas Gregor3447e762009-08-20 22:52:58 +00001577 // If we have declared a member function template, set the access of the
1578 // templated declaration as well.
1579 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1580 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001581 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001582
Anders Carlsson13a69102011-01-20 04:34:22 +00001583 if (VS.isOverrideSpecified()) {
1584 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1585 if (!MD || !MD->isVirtual()) {
1586 Diag(Member->getLocStart(),
1587 diag::override_keyword_only_allowed_on_virtual_member_functions)
1588 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001589 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001590 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001591 }
1592 if (VS.isFinalSpecified()) {
1593 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1594 if (!MD || !MD->isVirtual()) {
1595 Diag(Member->getLocStart(),
1596 diag::override_keyword_only_allowed_on_virtual_member_functions)
1597 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001598 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001599 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001600 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001601
Douglas Gregorf2f08062011-03-08 17:10:18 +00001602 if (VS.getLastLocation().isValid()) {
1603 // Update the end location of a method that has a virt-specifiers.
1604 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1605 MD->setRangeEnd(VS.getLastLocation());
1606 }
1607
Anders Carlssonc87f8612011-01-20 06:29:02 +00001608 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001609
Douglas Gregor92751d42008-11-17 22:58:34 +00001610 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001611
Douglas Gregor0c880302009-03-11 23:00:04 +00001612 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001613 AddInitializerToDecl(Member, Init, false,
1614 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith2316cd82011-09-29 19:11:37 +00001615 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1616 ActOnUninitializedDecl(Member, DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001617
Richard Smithb2bc2e62011-02-21 20:05:19 +00001618 FinalizeDeclaration(Member);
1619
John McCall25849ca2011-02-15 07:12:36 +00001620 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001621 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001622 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001623}
1624
Richard Smith938f40b2011-06-11 17:19:42 +00001625/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001626/// in-class initializer for a non-static C++ class member, and after
1627/// instantiating an in-class initializer in a class template. Such actions
1628/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001629void
1630Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1631 Expr *InitExpr) {
1632 FieldDecl *FD = cast<FieldDecl>(D);
1633
1634 if (!InitExpr) {
1635 FD->setInvalidDecl();
1636 FD->removeInClassInitializer();
1637 return;
1638 }
1639
1640 ExprResult Init = InitExpr;
1641 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1642 // FIXME: if there is no EqualLoc, this is list-initialization.
1643 Init = PerformCopyInitialization(
1644 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1645 if (Init.isInvalid()) {
1646 FD->setInvalidDecl();
1647 return;
1648 }
1649
1650 CheckImplicitConversions(Init.get(), EqualLoc);
1651 }
1652
1653 // C++0x [class.base.init]p7:
1654 // The initialization of each base and member constitutes a
1655 // full-expression.
1656 Init = MaybeCreateExprWithCleanups(Init);
1657 if (Init.isInvalid()) {
1658 FD->setInvalidDecl();
1659 return;
1660 }
1661
1662 InitExpr = Init.release();
1663
1664 FD->setInClassInitializer(InitExpr);
1665}
1666
Douglas Gregor15e77a22009-12-31 09:10:24 +00001667/// \brief Find the direct and/or virtual base specifiers that
1668/// correspond to the given base type, for use in base initialization
1669/// within a constructor.
1670static bool FindBaseInitializer(Sema &SemaRef,
1671 CXXRecordDecl *ClassDecl,
1672 QualType BaseType,
1673 const CXXBaseSpecifier *&DirectBaseSpec,
1674 const CXXBaseSpecifier *&VirtualBaseSpec) {
1675 // First, check for a direct base class.
1676 DirectBaseSpec = 0;
1677 for (CXXRecordDecl::base_class_const_iterator Base
1678 = ClassDecl->bases_begin();
1679 Base != ClassDecl->bases_end(); ++Base) {
1680 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1681 // We found a direct base of this type. That's what we're
1682 // initializing.
1683 DirectBaseSpec = &*Base;
1684 break;
1685 }
1686 }
1687
1688 // Check for a virtual base class.
1689 // FIXME: We might be able to short-circuit this if we know in advance that
1690 // there are no virtual bases.
1691 VirtualBaseSpec = 0;
1692 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1693 // We haven't found a base yet; search the class hierarchy for a
1694 // virtual base class.
1695 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1696 /*DetectVirtual=*/false);
1697 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1698 BaseType, Paths)) {
1699 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1700 Path != Paths.end(); ++Path) {
1701 if (Path->back().Base->isVirtual()) {
1702 VirtualBaseSpec = Path->back().Base;
1703 break;
1704 }
1705 }
1706 }
1707 }
1708
1709 return DirectBaseSpec || VirtualBaseSpec;
1710}
1711
Sebastian Redla74948d2011-09-24 17:48:25 +00001712/// \brief Handle a C++ member initializer using braced-init-list syntax.
1713MemInitResult
1714Sema::ActOnMemInitializer(Decl *ConstructorD,
1715 Scope *S,
1716 CXXScopeSpec &SS,
1717 IdentifierInfo *MemberOrBase,
1718 ParsedType TemplateTypeTy,
1719 SourceLocation IdLoc,
1720 Expr *InitList,
1721 SourceLocation EllipsisLoc) {
1722 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1723 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1724}
1725
1726/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001727MemInitResult
John McCall48871652010-08-21 09:40:31 +00001728Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001729 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001730 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001731 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001732 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001733 SourceLocation IdLoc,
1734 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001735 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001736 SourceLocation RParenLoc,
1737 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001738 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1739 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1740 RParenLoc),
1741 EllipsisLoc);
1742}
1743
1744/// \brief Handle a C++ member initializer.
1745MemInitResult
1746Sema::BuildMemInitializer(Decl *ConstructorD,
1747 Scope *S,
1748 CXXScopeSpec &SS,
1749 IdentifierInfo *MemberOrBase,
1750 ParsedType TemplateTypeTy,
1751 SourceLocation IdLoc,
1752 const MultiInitializer &Args,
1753 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001754 if (!ConstructorD)
1755 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001756
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001757 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001758
1759 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001760 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001761 if (!Constructor) {
1762 // The user wrote a constructor initializer on a function that is
1763 // not a C++ constructor. Ignore the error for now, because we may
1764 // have more member initializers coming; we'll diagnose it just
1765 // once in ActOnMemInitializers.
1766 return true;
1767 }
1768
1769 CXXRecordDecl *ClassDecl = Constructor->getParent();
1770
1771 // C++ [class.base.init]p2:
1772 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001773 // constructor's class and, if not found in that scope, are looked
1774 // up in the scope containing the constructor's definition.
1775 // [Note: if the constructor's class contains a member with the
1776 // same name as a direct or virtual base class of the class, a
1777 // mem-initializer-id naming the member or base class and composed
1778 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001779 // mem-initializer-id for the hidden base class may be specified
1780 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001781 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001782 // Look for a member, first.
1783 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001784 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001785 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001786 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001787 Member = dyn_cast<FieldDecl>(*Result.first);
Sebastian Redla74948d2011-09-24 17:48:25 +00001788
Douglas Gregor44e7df62011-01-04 00:32:56 +00001789 if (Member) {
1790 if (EllipsisLoc.isValid())
1791 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001792 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1793
1794 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001795 }
Sebastian Redla74948d2011-09-24 17:48:25 +00001796
Francois Pichetd583da02010-12-04 09:14:42 +00001797 // Handle anonymous union case.
1798 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001799 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1800 if (EllipsisLoc.isValid())
1801 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001802 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor44e7df62011-01-04 00:32:56 +00001803
Sebastian Redla74948d2011-09-24 17:48:25 +00001804 return BuildMemberInitializer(IndirectField, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001805 }
Francois Pichetd583da02010-12-04 09:14:42 +00001806 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001807 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001808 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001809 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001810 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001811
1812 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001813 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001814 } else {
1815 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1816 LookupParsedName(R, S, &SS);
1817
1818 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1819 if (!TyD) {
1820 if (R.isAmbiguous()) return true;
1821
John McCallda6841b2010-04-09 19:01:14 +00001822 // We don't want access-control diagnostics here.
1823 R.suppressDiagnostics();
1824
Douglas Gregora3b624a2010-01-19 06:46:48 +00001825 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1826 bool NotUnknownSpecialization = false;
1827 DeclContext *DC = computeDeclContext(SS, false);
1828 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1829 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1830
1831 if (!NotUnknownSpecialization) {
1832 // When the scope specifier can refer to a member of an unknown
1833 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001834 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1835 SS.getWithLocInContext(Context),
1836 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001837 if (BaseType.isNull())
1838 return true;
1839
Douglas Gregora3b624a2010-01-19 06:46:48 +00001840 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001841 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001842 }
1843 }
1844
Douglas Gregor15e77a22009-12-31 09:10:24 +00001845 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001846 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00001847 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001848 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1849 ClassDecl, false, CTC_NoKeywords))) {
1850 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1851 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1852 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001853 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001854 // We have found a non-static data member with a similar
1855 // name to what was typed; complain and initialize that
1856 // member.
1857 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001858 << MemberOrBase << true << CorrectedQuotedStr
1859 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor6da83622010-01-07 00:17:44 +00001860 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001861 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001862
Sebastian Redla74948d2011-09-24 17:48:25 +00001863 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor15e77a22009-12-31 09:10:24 +00001864 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001865 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001866 const CXXBaseSpecifier *DirectBaseSpec;
1867 const CXXBaseSpecifier *VirtualBaseSpec;
1868 if (FindBaseInitializer(*this, ClassDecl,
1869 Context.getTypeDeclType(Type),
1870 DirectBaseSpec, VirtualBaseSpec)) {
1871 // We have found a direct or virtual base class with a
1872 // similar name to what was typed; complain and initialize
1873 // that base class.
1874 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001875 << MemberOrBase << false << CorrectedQuotedStr
1876 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001877
1878 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1879 : VirtualBaseSpec;
1880 Diag(BaseSpec->getSourceRange().getBegin(),
1881 diag::note_base_class_specified_here)
1882 << BaseSpec->getType()
1883 << BaseSpec->getSourceRange();
1884
Douglas Gregor15e77a22009-12-31 09:10:24 +00001885 TyD = Type;
1886 }
1887 }
1888 }
1889
Douglas Gregora3b624a2010-01-19 06:46:48 +00001890 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001891 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla74948d2011-09-24 17:48:25 +00001892 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001893 return true;
1894 }
John McCallb5a0d312009-12-21 10:41:20 +00001895 }
1896
Douglas Gregora3b624a2010-01-19 06:46:48 +00001897 if (BaseType.isNull()) {
1898 BaseType = Context.getTypeDeclType(TyD);
1899 if (SS.isSet()) {
1900 NestedNameSpecifier *Qualifier =
1901 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001902
Douglas Gregora3b624a2010-01-19 06:46:48 +00001903 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001904 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001905 }
John McCallb5a0d312009-12-21 10:41:20 +00001906 }
1907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908
John McCallbcd03502009-12-07 02:54:59 +00001909 if (!TInfo)
1910 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001911
Sebastian Redla74948d2011-09-24 17:48:25 +00001912 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001913}
1914
Chandler Carruth599deef2011-09-03 01:14:15 +00001915/// Checks a member initializer expression for cases where reference (or
1916/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001917static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1918 Expr *Init,
1919 SourceLocation IdLoc) {
1920 QualType MemberTy = Member->getType();
1921
1922 // We only handle pointers and references currently.
1923 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1924 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1925 return;
1926
1927 const bool IsPointer = MemberTy->isPointerType();
1928 if (IsPointer) {
1929 if (const UnaryOperator *Op
1930 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1931 // The only case we're worried about with pointers requires taking the
1932 // address.
1933 if (Op->getOpcode() != UO_AddrOf)
1934 return;
1935
1936 Init = Op->getSubExpr();
1937 } else {
1938 // We only handle address-of expression initializers for pointers.
1939 return;
1940 }
1941 }
1942
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001943 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1944 // Taking the address of a temporary will be diagnosed as a hard error.
1945 if (IsPointer)
1946 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001947
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001948 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1949 << Member << Init->getSourceRange();
1950 } else if (const DeclRefExpr *DRE
1951 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1952 // We only warn when referring to a non-reference parameter declaration.
1953 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1954 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00001955 return;
1956
1957 S.Diag(Init->getExprLoc(),
1958 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1959 : diag::warn_bind_ref_member_to_parameter)
1960 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001961 } else {
1962 // Other initializers are fine.
1963 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001964 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001965
1966 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1967 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00001968}
1969
John McCalle22a04a2009-11-04 23:02:40 +00001970/// Checks an initializer expression for use of uninitialized fields, such as
1971/// containing the field that is being initialized. Returns true if there is an
1972/// uninitialized field was used an updates the SourceLocation parameter; false
1973/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001974static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001975 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001976 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001977 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1978
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001979 if (isa<CallExpr>(S)) {
1980 // Do not descend into function calls or constructors, as the use
1981 // of an uninitialized field may be valid. One would have to inspect
1982 // the contents of the function/ctor to determine if it is safe or not.
1983 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1984 // may be safe, depending on what the function/ctor does.
1985 return false;
1986 }
1987 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1988 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001989
1990 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1991 // The member expression points to a static data member.
1992 assert(VD->isStaticDataMember() &&
1993 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001994 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001995 return false;
1996 }
1997
1998 if (isa<EnumConstantDecl>(RhsField)) {
1999 // The member expression points to an enum.
2000 return false;
2001 }
2002
John McCalle22a04a2009-11-04 23:02:40 +00002003 if (RhsField == LhsField) {
2004 // Initializing a field with itself. Throw a warning.
2005 // But wait; there are exceptions!
2006 // Exception #1: The field may not belong to this record.
2007 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002008 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00002009 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2010 // Even though the field matches, it does not belong to this record.
2011 return false;
2012 }
2013 // None of the exceptions triggered; return true to indicate an
2014 // uninitialized field was used.
2015 *L = ME->getMemberLoc();
2016 return true;
2017 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002018 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00002019 // sizeof/alignof doesn't reference contents, do not warn.
2020 return false;
2021 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2022 // address-of doesn't reference contents (the pointer may be dereferenced
2023 // in the same expression but it would be rare; and weird).
2024 if (UOE->getOpcode() == UO_AddrOf)
2025 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002026 }
John McCall8322c3a2011-02-13 04:07:26 +00002027 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002028 if (!*it) {
2029 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00002030 continue;
2031 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002032 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2033 return true;
John McCalle22a04a2009-11-04 23:02:40 +00002034 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002035 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002036}
2037
John McCallfaf5fb42010-08-26 23:41:50 +00002038MemInitResult
Sebastian Redla74948d2011-09-24 17:48:25 +00002039Sema::BuildMemberInitializer(ValueDecl *Member,
2040 const MultiInitializer &Args,
2041 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002042 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2043 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2044 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002045 "Member must be a FieldDecl or IndirectFieldDecl");
2046
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002047 if (Member->isInvalidDecl())
2048 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002049
John McCalle22a04a2009-11-04 23:02:40 +00002050 // Diagnose value-uses of fields to initialize themselves, e.g.
2051 // foo(foo)
2052 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002053 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla74948d2011-09-24 17:48:25 +00002054 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2055 I != E; ++I) {
John McCalle22a04a2009-11-04 23:02:40 +00002056 SourceLocation L;
Sebastian Redla74948d2011-09-24 17:48:25 +00002057 Expr *Arg = *I;
2058 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2059 Arg = DIE->getInit();
2060 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00002061 // FIXME: Return true in the case when other fields are used before being
2062 // uninitialized. For example, let this field be the i'th field. When
2063 // initializing the i'th field, throw a warning if any of the >= i'th
2064 // fields are used, as they are not yet initialized.
2065 // Right now we are only handling the case where the i'th field uses
2066 // itself in its initializer.
2067 Diag(L, diag::warn_field_is_uninit);
2068 }
2069 }
2070
Sebastian Redla74948d2011-09-24 17:48:25 +00002071 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002072
Chandler Carruthd44c3102010-12-06 09:23:57 +00002073 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00002074 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002075 // Can't check initialization for a member of dependent type or when
2076 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002077 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002078
John McCall31168b02011-06-15 23:02:42 +00002079 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002080 } else {
2081 // Initialize the member.
2082 InitializedEntity MemberEntity =
2083 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2084 : InitializedEntity::InitializeMember(IndirectMember, 0);
2085 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002086 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2087 Args.getEndLoc());
John McCallacf0ee52010-10-08 02:01:28 +00002088
Sebastian Redla74948d2011-09-24 17:48:25 +00002089 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002090 if (MemberInit.isInvalid())
2091 return true;
2092
Sebastian Redla74948d2011-09-24 17:48:25 +00002093 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002094
2095 // C++0x [class.base.init]p7:
2096 // The initialization of each base and member constitutes a
2097 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002098 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002099 if (MemberInit.isInvalid())
2100 return true;
2101
2102 // If we are in a dependent context, template instantiation will
2103 // perform this type-checking again. Just save the arguments that we
2104 // received in a ParenListExpr.
2105 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2106 // of the information that we have about the member
2107 // initializer. However, deconstructing the ASTs is a dicey process,
2108 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00002109 if (CurContext->isDependentContext()) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002110 Init = Args.CreateInitExpr(Context,
2111 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00002112 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002113 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00002114 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2115 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002116 }
2117
Chandler Carruthd44c3102010-12-06 09:23:57 +00002118 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002119 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002120 IdLoc, Args.getStartLoc(),
2121 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002122 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00002123 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002124 IdLoc, Args.getStartLoc(),
2125 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002126 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002127}
2128
John McCallfaf5fb42010-08-26 23:41:50 +00002129MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002130Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002131 const MultiInitializer &Args,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002132 SourceLocation NameLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002133 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002134 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2135 if (!LangOpts.CPlusPlus0x)
2136 return Diag(Loc, diag::err_delegation_0x_only)
2137 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002138
Alexis Huntc5575cc2011-02-26 19:13:13 +00002139 // Initialize the object.
2140 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2141 QualType(ClassDecl->getTypeForDecl(), 0));
2142 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002143 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2144 Args.getEndLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002145
Sebastian Redla74948d2011-09-24 17:48:25 +00002146 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002147 if (DelegationInit.isInvalid())
2148 return true;
2149
2150 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00002151 CXXConstructorDecl *Constructor
2152 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002153 assert(Constructor && "Delegating constructor with no target?");
2154
Sebastian Redla74948d2011-09-24 17:48:25 +00002155 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002156
2157 // C++0x [class.base.init]p7:
2158 // The initialization of each base and member constitutes a
2159 // full-expression.
2160 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2161 if (DelegationInit.isInvalid())
2162 return true;
2163
Manuel Klimekf2b4b692011-06-22 20:02:16 +00002164 assert(!CurContext->isDependentContext());
Sebastian Redla74948d2011-09-24 17:48:25 +00002165 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
2166 Constructor,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002167 DelegationInit.takeAs<Expr>(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002168 Args.getEndLoc());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002169}
2170
2171MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002172Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002173 const MultiInitializer &Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002174 CXXRecordDecl *ClassDecl,
2175 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002176 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002177
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002178 SourceLocation BaseLoc
2179 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002180
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002181 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2182 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2183 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2184
2185 // C++ [class.base.init]p2:
2186 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002187 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002188 // of that class, the mem-initializer is ill-formed. A
2189 // mem-initializer-list can initialize a base class using any
2190 // name that denotes that base class type.
2191 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2192
Douglas Gregor44e7df62011-01-04 00:32:56 +00002193 if (EllipsisLoc.isValid()) {
2194 // This is a pack expansion.
2195 if (!BaseType->containsUnexpandedParameterPack()) {
2196 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla74948d2011-09-24 17:48:25 +00002197 << SourceRange(BaseLoc, Args.getEndLoc());
2198
Douglas Gregor44e7df62011-01-04 00:32:56 +00002199 EllipsisLoc = SourceLocation();
2200 }
2201 } else {
2202 // Check for any unexpanded parameter packs.
2203 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2204 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002205
2206 if (Args.DiagnoseUnexpandedParameterPack(*this))
2207 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002208 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002209
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002210 // Check for direct and virtual base classes.
2211 const CXXBaseSpecifier *DirectBaseSpec = 0;
2212 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2213 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002214 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2215 BaseType))
Sebastian Redla74948d2011-09-24 17:48:25 +00002216 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002217
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002218 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2219 VirtualBaseSpec);
2220
2221 // C++ [base.class.init]p2:
2222 // Unless the mem-initializer-id names a nonstatic data member of the
2223 // constructor's class or a direct or virtual base of that class, the
2224 // mem-initializer is ill-formed.
2225 if (!DirectBaseSpec && !VirtualBaseSpec) {
2226 // If the class has any dependent bases, then it's possible that
2227 // one of those types will resolve to the same type as
2228 // BaseType. Therefore, just treat this as a dependent base
2229 // class initialization. FIXME: Should we try to check the
2230 // initialization anyway? It seems odd.
2231 if (ClassDecl->hasAnyDependentBases())
2232 Dependent = true;
2233 else
2234 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2235 << BaseType << Context.getTypeDeclType(ClassDecl)
2236 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2237 }
2238 }
2239
2240 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002241 // Can't check initialization for a base of dependent type or when
2242 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002243 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002244
John McCall31168b02011-06-15 23:02:42 +00002245 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002246
Sebastian Redla74948d2011-09-24 17:48:25 +00002247 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2248 /*IsVirtual=*/false,
2249 Args.getStartLoc(), BaseInit,
2250 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002251 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002252
2253 // C++ [base.class.init]p2:
2254 // If a mem-initializer-id is ambiguous because it designates both
2255 // a direct non-virtual base class and an inherited virtual base
2256 // class, the mem-initializer is ill-formed.
2257 if (DirectBaseSpec && VirtualBaseSpec)
2258 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002259 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002260
2261 CXXBaseSpecifier *BaseSpec
2262 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2263 if (!BaseSpec)
2264 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2265
2266 // Initialize the base.
2267 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00002268 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002269 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002270 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2271 Args.getEndLoc());
2272
2273 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002274 if (BaseInit.isInvalid())
2275 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002276
Sebastian Redla74948d2011-09-24 17:48:25 +00002277 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2278
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002279 // C++0x [class.base.init]p7:
2280 // The initialization of each base and member constitutes a
2281 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002282 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002283 if (BaseInit.isInvalid())
2284 return true;
2285
2286 // If we are in a dependent context, template instantiation will
2287 // perform this type-checking again. Just save the arguments that we
2288 // received in a ParenListExpr.
2289 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2290 // of the information that we have about the base
2291 // initializer. However, deconstructing the ASTs is a dicey process,
2292 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002293 if (CurContext->isDependentContext())
2294 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002295
Alexis Hunt1d792652011-01-08 20:30:50 +00002296 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002297 BaseSpec->isVirtual(),
2298 Args.getStartLoc(),
2299 BaseInit.takeAs<Expr>(),
2300 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002301}
2302
Sebastian Redl22653ba2011-08-30 19:58:05 +00002303// Create a static_cast\<T&&>(expr).
2304static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2305 QualType ExprType = E->getType();
2306 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2307 SourceLocation ExprLoc = E->getLocStart();
2308 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2309 TargetType, ExprLoc);
2310
2311 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2312 SourceRange(ExprLoc, ExprLoc),
2313 E->getSourceRange()).take();
2314}
2315
Anders Carlsson1b00e242010-04-23 03:10:23 +00002316/// ImplicitInitializerKind - How an implicit base or member initializer should
2317/// initialize its base or member.
2318enum ImplicitInitializerKind {
2319 IIK_Default,
2320 IIK_Copy,
2321 IIK_Move
2322};
2323
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002324static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002325BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002326 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002327 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002328 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002329 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002330 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002331 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2332 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002333
John McCalldadc5752010-08-24 06:29:42 +00002334 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002335
2336 switch (ImplicitInitKind) {
2337 case IIK_Default: {
2338 InitializationKind InitKind
2339 = InitializationKind::CreateDefault(Constructor->getLocation());
2340 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2341 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002342 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002343 break;
2344 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002345
Sebastian Redl22653ba2011-08-30 19:58:05 +00002346 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002347 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002348 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002349 ParmVarDecl *Param = Constructor->getParamDecl(0);
2350 QualType ParamType = Param->getType().getNonReferenceType();
2351
2352 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00002353 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002354 Constructor->getLocation(), ParamType,
2355 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002356
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002357 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002358 QualType ArgTy =
2359 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2360 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002361
Sebastian Redl22653ba2011-08-30 19:58:05 +00002362 if (Moving) {
2363 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2364 }
2365
John McCallcf142162010-08-07 06:22:56 +00002366 CXXCastPath BasePath;
2367 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002368 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2369 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002370 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002371 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002372
Anders Carlsson1b00e242010-04-23 03:10:23 +00002373 InitializationKind InitKind
2374 = InitializationKind::CreateDirect(Constructor->getLocation(),
2375 SourceLocation(), SourceLocation());
2376 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2377 &CopyCtorArg, 1);
2378 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002379 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002380 break;
2381 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002382 }
John McCallb268a282010-08-23 23:25:46 +00002383
Douglas Gregora40433a2010-12-07 00:41:46 +00002384 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002385 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002386 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002387
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002388 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002389 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002390 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2391 SourceLocation()),
2392 BaseSpec->isVirtual(),
2393 SourceLocation(),
2394 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002395 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002396 SourceLocation());
2397
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002398 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002399}
2400
Sebastian Redl22653ba2011-08-30 19:58:05 +00002401static bool RefersToRValueRef(Expr *MemRef) {
2402 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2403 return Referenced->getType()->isRValueReferenceType();
2404}
2405
Anders Carlsson3c1db572010-04-23 02:15:47 +00002406static bool
2407BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002408 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002409 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002410 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002411 if (Field->isInvalidDecl())
2412 return true;
2413
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002414 SourceLocation Loc = Constructor->getLocation();
2415
Sebastian Redl22653ba2011-08-30 19:58:05 +00002416 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2417 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002418 ParmVarDecl *Param = Constructor->getParamDecl(0);
2419 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002420
2421 // Suppress copying zero-width bitfields.
2422 if (const Expr *Width = Field->getBitWidth())
2423 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2424 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002425
2426 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00002427 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002428 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002429
Sebastian Redl22653ba2011-08-30 19:58:05 +00002430 if (Moving) {
2431 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2432 }
2433
Douglas Gregor94f9a482010-05-05 05:51:00 +00002434 // Build a reference to this field within the parameter.
2435 CXXScopeSpec SS;
2436 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2437 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002438 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2439 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002440 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002441 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002442 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002443 ParamType, Loc,
2444 /*IsArrow=*/false,
2445 SS,
2446 /*FirstQualifierInScope=*/0,
2447 MemberLookup,
2448 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002449 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002450 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002451
2452 // C++11 [class.copy]p15:
2453 // - if a member m has rvalue reference type T&&, it is direct-initialized
2454 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002455 if (RefersToRValueRef(CtorArg.get())) {
2456 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002457 }
2458
Douglas Gregor94f9a482010-05-05 05:51:00 +00002459 // When the field we are copying is an array, create index variables for
2460 // each dimension of the array. We use these index variables to subscript
2461 // the source array, and other clients (e.g., CodeGen) will perform the
2462 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002463 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002464 QualType BaseType = Field->getType();
2465 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002466 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002467 while (const ConstantArrayType *Array
2468 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002469 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002470 // Create the iteration variable for this array index.
2471 IdentifierInfo *IterationVarName = 0;
2472 {
2473 llvm::SmallString<8> Str;
2474 llvm::raw_svector_ostream OS(Str);
2475 OS << "__i" << IndexVariables.size();
2476 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2477 }
2478 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002479 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002480 IterationVarName, SizeType,
2481 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002482 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002483 IndexVariables.push_back(IterationVar);
2484
2485 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002486 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002487 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002488 assert(!IterationVarRef.isInvalid() &&
2489 "Reference to invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002490
Douglas Gregor94f9a482010-05-05 05:51:00 +00002491 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002492 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002493 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002494 Loc);
2495 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002496 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002497
Douglas Gregor94f9a482010-05-05 05:51:00 +00002498 BaseType = Array->getElementType();
2499 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002500
2501 // The array subscript expression is an lvalue, which is wrong for moving.
2502 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002503 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002504
Douglas Gregor94f9a482010-05-05 05:51:00 +00002505 // Construct the entity that we will be initializing. For an array, this
2506 // will be first element in the array, which may require several levels
2507 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002508 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002509 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002510 if (Indirect)
2511 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2512 else
2513 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002514 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2515 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2516 0,
2517 Entities.back()));
2518
2519 // Direct-initialize to use the copy constructor.
2520 InitializationKind InitKind =
2521 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2522
Sebastian Redle9c4e842011-09-04 18:14:28 +00002523 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002524 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002525 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002526
John McCalldadc5752010-08-24 06:29:42 +00002527 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002528 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002529 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002530 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002531 if (MemberInit.isInvalid())
2532 return true;
2533
Douglas Gregor493627b2011-08-10 15:22:55 +00002534 if (Indirect) {
2535 assert(IndexVariables.size() == 0 &&
2536 "Indirect field improperly initialized");
2537 CXXMemberInit
2538 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2539 Loc, Loc,
2540 MemberInit.takeAs<Expr>(),
2541 Loc);
2542 } else
2543 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2544 Loc, MemberInit.takeAs<Expr>(),
2545 Loc,
2546 IndexVariables.data(),
2547 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002548 return false;
2549 }
2550
Anders Carlsson423f5d82010-04-23 16:04:08 +00002551 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2552
Anders Carlsson3c1db572010-04-23 02:15:47 +00002553 QualType FieldBaseElementType =
2554 SemaRef.Context.getBaseElementType(Field->getType());
2555
Anders Carlsson3c1db572010-04-23 02:15:47 +00002556 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002557 InitializedEntity InitEntity
2558 = Indirect? InitializedEntity::InitializeMember(Indirect)
2559 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002560 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002561 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002562
2563 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002564 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002565 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002566
Douglas Gregora40433a2010-12-07 00:41:46 +00002567 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002568 if (MemberInit.isInvalid())
2569 return true;
2570
Douglas Gregor493627b2011-08-10 15:22:55 +00002571 if (Indirect)
2572 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2573 Indirect, Loc,
2574 Loc,
2575 MemberInit.get(),
2576 Loc);
2577 else
2578 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2579 Field, Loc, Loc,
2580 MemberInit.get(),
2581 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002582 return false;
2583 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002584
Alexis Hunt8b455182011-05-17 00:19:05 +00002585 if (!Field->getParent()->isUnion()) {
2586 if (FieldBaseElementType->isReferenceType()) {
2587 SemaRef.Diag(Constructor->getLocation(),
2588 diag::err_uninitialized_member_in_ctor)
2589 << (int)Constructor->isImplicit()
2590 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2591 << 0 << Field->getDeclName();
2592 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2593 return true;
2594 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002595
Alexis Hunt8b455182011-05-17 00:19:05 +00002596 if (FieldBaseElementType.isConstQualified()) {
2597 SemaRef.Diag(Constructor->getLocation(),
2598 diag::err_uninitialized_member_in_ctor)
2599 << (int)Constructor->isImplicit()
2600 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2601 << 1 << Field->getDeclName();
2602 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2603 return true;
2604 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002605 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002606
John McCall31168b02011-06-15 23:02:42 +00002607 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2608 FieldBaseElementType->isObjCRetainableType() &&
2609 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2610 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2611 // Instant objects:
2612 // Default-initialize Objective-C pointers to NULL.
2613 CXXMemberInit
2614 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2615 Loc, Loc,
2616 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2617 Loc);
2618 return false;
2619 }
2620
Anders Carlsson3c1db572010-04-23 02:15:47 +00002621 // Nothing to initialize.
2622 CXXMemberInit = 0;
2623 return false;
2624}
John McCallbc83b3f2010-05-20 23:23:51 +00002625
2626namespace {
2627struct BaseAndFieldInfo {
2628 Sema &S;
2629 CXXConstructorDecl *Ctor;
2630 bool AnyErrorsInInits;
2631 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002632 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002633 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002634
2635 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2636 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002637 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2638 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002639 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002640 else if (Generated && Ctor->isMoveConstructor())
2641 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002642 else
2643 IIK = IIK_Default;
2644 }
2645};
2646}
2647
Richard Smithc94ec842011-09-19 13:34:43 +00002648/// \brief Determine whether the given indirect field declaration is somewhere
2649/// within an anonymous union.
2650static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2651 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2652 CEnd = F->chain_end();
2653 C != CEnd; ++C)
2654 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2655 if (Record->isUnion())
2656 return true;
2657
2658 return false;
2659}
2660
Richard Smith938f40b2011-06-11 17:19:42 +00002661static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002662 FieldDecl *Field,
2663 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002664
Chandler Carruth139e9622010-06-30 02:59:29 +00002665 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002666 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002667 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002668 return false;
2669 }
2670
Richard Smith938f40b2011-06-11 17:19:42 +00002671 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2672 // has a brace-or-equal-initializer, the entity is initialized as specified
2673 // in [dcl.init].
2674 if (Field->hasInClassInitializer()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002675 CXXCtorInitializer *Init;
2676 if (Indirect)
2677 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2678 SourceLocation(),
2679 SourceLocation(), 0,
2680 SourceLocation());
2681 else
2682 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2683 SourceLocation(),
2684 SourceLocation(), 0,
2685 SourceLocation());
2686 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002687 return false;
2688 }
2689
Richard Smith12d5ed82011-09-18 11:14:50 +00002690 // Don't build an implicit initializer for union members if none was
2691 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002692 if (Field->getParent()->isUnion() ||
2693 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002694 return false;
2695
John McCallbc83b3f2010-05-20 23:23:51 +00002696 // Don't try to build an implicit initializer if there were semantic
2697 // errors in any of the initializers (and therefore we might be
2698 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002699 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002700 return false;
2701
Alexis Hunt1d792652011-01-08 20:30:50 +00002702 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002703 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2704 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002705 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002706
Francois Pichetd583da02010-12-04 09:14:42 +00002707 if (Init)
2708 Info.AllToInit.push_back(Init);
2709
John McCallbc83b3f2010-05-20 23:23:51 +00002710 return false;
2711}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002712
2713bool
2714Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2715 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002716 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002717 Constructor->setNumCtorInitializers(1);
2718 CXXCtorInitializer **initializer =
2719 new (Context) CXXCtorInitializer*[1];
2720 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2721 Constructor->setCtorInitializers(initializer);
2722
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002723 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2724 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2725 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2726 }
2727
Alexis Hunte2622992011-05-05 00:05:47 +00002728 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002729
Alexis Hunt61bc1732011-05-01 07:04:31 +00002730 return false;
2731}
Douglas Gregor493627b2011-08-10 15:22:55 +00002732
John McCall1b1a1db2011-06-17 00:18:42 +00002733bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2734 CXXCtorInitializer **Initializers,
2735 unsigned NumInitializers,
2736 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002737 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002738 // Just store the initializers as written, they will be checked during
2739 // instantiation.
2740 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002741 Constructor->setNumCtorInitializers(NumInitializers);
2742 CXXCtorInitializer **baseOrMemberInitializers =
2743 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002744 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002745 NumInitializers * sizeof(CXXCtorInitializer*));
2746 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002747 }
2748
2749 return false;
2750 }
2751
John McCallbc83b3f2010-05-20 23:23:51 +00002752 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002753
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002754 // We need to build the initializer AST according to order of construction
2755 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002756 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002757 if (!ClassDecl)
2758 return true;
2759
Eli Friedman9cf6b592009-11-09 19:20:36 +00002760 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002761
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002762 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002763 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002764
2765 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002766 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002767 else
Francois Pichetd583da02010-12-04 09:14:42 +00002768 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002769 }
2770
Anders Carlsson43c64af2010-04-21 19:52:01 +00002771 // Keep track of the direct virtual bases.
2772 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2773 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2774 E = ClassDecl->bases_end(); I != E; ++I) {
2775 if (I->isVirtual())
2776 DirectVBases.insert(I);
2777 }
2778
Anders Carlssondb0a9652010-04-02 06:26:44 +00002779 // Push virtual bases before others.
2780 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2781 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2782
Alexis Hunt1d792652011-01-08 20:30:50 +00002783 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002784 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2785 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002786 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002787 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002788 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002789 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002790 VBase, IsInheritedVirtualBase,
2791 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002792 HadError = true;
2793 continue;
2794 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002795
John McCallbc83b3f2010-05-20 23:23:51 +00002796 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002797 }
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
John McCallbc83b3f2010-05-20 23:23:51 +00002800 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002801 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2802 E = ClassDecl->bases_end(); Base != E; ++Base) {
2803 // Virtuals are in the virtual base list and already constructed.
2804 if (Base->isVirtual())
2805 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002806
Alexis Hunt1d792652011-01-08 20:30:50 +00002807 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002808 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2809 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002810 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002811 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002812 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002813 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002814 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002815 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002816 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002817 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002818
John McCallbc83b3f2010-05-20 23:23:51 +00002819 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002820 }
2821 }
Mike Stump11289f42009-09-09 15:08:12 +00002822
John McCallbc83b3f2010-05-20 23:23:51 +00002823 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002824 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2825 MemEnd = ClassDecl->decls_end();
2826 Mem != MemEnd; ++Mem) {
2827 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2828 if (F->getType()->isIncompleteArrayType()) {
2829 assert(ClassDecl->hasFlexibleArrayMember() &&
2830 "Incomplete array type is not valid");
2831 continue;
2832 }
2833
Sebastian Redl22653ba2011-08-30 19:58:05 +00002834 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002835 // handle anonymous struct/union fields based on their individual
2836 // indirect fields.
2837 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2838 continue;
2839
2840 if (CollectFieldInitializer(*this, Info, F))
2841 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002842 continue;
2843 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002844
2845 // Beyond this point, we only consider default initialization.
2846 if (Info.IIK != IIK_Default)
2847 continue;
2848
2849 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2850 if (F->getType()->isIncompleteArrayType()) {
2851 assert(ClassDecl->hasFlexibleArrayMember() &&
2852 "Incomplete array type is not valid");
2853 continue;
2854 }
2855
Douglas Gregor493627b2011-08-10 15:22:55 +00002856 // Initialize each field of an anonymous struct individually.
2857 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2858 HadError = true;
2859
2860 continue;
2861 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002862 }
Mike Stump11289f42009-09-09 15:08:12 +00002863
John McCallbc83b3f2010-05-20 23:23:51 +00002864 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002865 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002866 Constructor->setNumCtorInitializers(NumInitializers);
2867 CXXCtorInitializer **baseOrMemberInitializers =
2868 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002869 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002870 NumInitializers * sizeof(CXXCtorInitializer*));
2871 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002872
John McCalla6309952010-03-16 21:39:52 +00002873 // Constructors implicitly reference the base and member
2874 // destructors.
2875 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2876 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002877 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002878
2879 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002880}
2881
Eli Friedman952c15d2009-07-21 19:28:10 +00002882static void *GetKeyForTopLevelField(FieldDecl *Field) {
2883 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002884 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002885 if (RT->getDecl()->isAnonymousStructOrUnion())
2886 return static_cast<void *>(RT->getDecl());
2887 }
2888 return static_cast<void *>(Field);
2889}
2890
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002891static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002892 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002893}
2894
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002895static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002896 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002897 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002898 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002899
Eli Friedman952c15d2009-07-21 19:28:10 +00002900 // For fields injected into the class via declaration of an anonymous union,
2901 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002902 FieldDecl *Field = Member->getAnyMember();
2903
John McCall23eebd92010-04-10 09:28:51 +00002904 // If the field is a member of an anonymous struct or union, our key
2905 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002906 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002907 if (RD->isAnonymousStructOrUnion()) {
2908 while (true) {
2909 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2910 if (Parent->isAnonymousStructOrUnion())
2911 RD = Parent;
2912 else
2913 break;
2914 }
2915
Anders Carlsson83ac3122010-03-30 16:19:37 +00002916 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002917 }
Mike Stump11289f42009-09-09 15:08:12 +00002918
Anders Carlssona942dcd2010-03-30 15:39:27 +00002919 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002920}
2921
Anders Carlssone857b292010-04-02 03:37:03 +00002922static void
2923DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002924 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002925 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002926 unsigned NumInits) {
2927 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002928 return;
Mike Stump11289f42009-09-09 15:08:12 +00002929
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002930 // Don't check initializers order unless the warning is enabled at the
2931 // location of at least one initializer.
2932 bool ShouldCheckOrder = false;
2933 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002934 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002935 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2936 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00002937 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002938 ShouldCheckOrder = true;
2939 break;
2940 }
2941 }
2942 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002943 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002944
John McCallbb7b6582010-04-10 07:37:23 +00002945 // Build the list of bases and members in the order that they'll
2946 // actually be initialized. The explicit initializers should be in
2947 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002948 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002949
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002950 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2951
John McCallbb7b6582010-04-10 07:37:23 +00002952 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002953 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002954 ClassDecl->vbases_begin(),
2955 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002956 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002957
John McCallbb7b6582010-04-10 07:37:23 +00002958 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002959 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002960 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002961 if (Base->isVirtual())
2962 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002963 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002964 }
Mike Stump11289f42009-09-09 15:08:12 +00002965
John McCallbb7b6582010-04-10 07:37:23 +00002966 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002967 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2968 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002969 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002970
John McCallbb7b6582010-04-10 07:37:23 +00002971 unsigned NumIdealInits = IdealInitKeys.size();
2972 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002973
Alexis Hunt1d792652011-01-08 20:30:50 +00002974 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002975 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002976 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002977 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002978
2979 // Scan forward to try to find this initializer in the idealized
2980 // initializers list.
2981 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2982 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002983 break;
John McCallbb7b6582010-04-10 07:37:23 +00002984
2985 // If we didn't find this initializer, it must be because we
2986 // scanned past it on a previous iteration. That can only
2987 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002988 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002989 Sema::SemaDiagnosticBuilder D =
2990 SemaRef.Diag(PrevInit->getSourceLocation(),
2991 diag::warn_initializer_out_of_order);
2992
Francois Pichetd583da02010-12-04 09:14:42 +00002993 if (PrevInit->isAnyMemberInitializer())
2994 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002995 else
2996 D << 1 << PrevInit->getBaseClassInfo()->getType();
2997
Francois Pichetd583da02010-12-04 09:14:42 +00002998 if (Init->isAnyMemberInitializer())
2999 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003000 else
3001 D << 1 << Init->getBaseClassInfo()->getType();
3002
3003 // Move back to the initializer's location in the ideal list.
3004 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3005 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003006 break;
John McCallbb7b6582010-04-10 07:37:23 +00003007
3008 assert(IdealIndex != NumIdealInits &&
3009 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003010 }
John McCallbb7b6582010-04-10 07:37:23 +00003011
3012 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003013 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003014}
3015
John McCall23eebd92010-04-10 09:28:51 +00003016namespace {
3017bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003018 CXXCtorInitializer *Init,
3019 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003020 if (!PrevInit) {
3021 PrevInit = Init;
3022 return false;
3023 }
3024
3025 if (FieldDecl *Field = Init->getMember())
3026 S.Diag(Init->getSourceLocation(),
3027 diag::err_multiple_mem_initialization)
3028 << Field->getDeclName()
3029 << Init->getSourceRange();
3030 else {
John McCall424cec92011-01-19 06:33:43 +00003031 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003032 assert(BaseClass && "neither field nor base");
3033 S.Diag(Init->getSourceLocation(),
3034 diag::err_multiple_base_initialization)
3035 << QualType(BaseClass, 0)
3036 << Init->getSourceRange();
3037 }
3038 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3039 << 0 << PrevInit->getSourceRange();
3040
3041 return true;
3042}
3043
Alexis Hunt1d792652011-01-08 20:30:50 +00003044typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003045typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3046
3047bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003048 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003049 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003050 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003051 RecordDecl *Parent = Field->getParent();
3052 if (!Parent->isAnonymousStructOrUnion())
3053 return false;
3054
3055 NamedDecl *Child = Field;
3056 do {
3057 if (Parent->isUnion()) {
3058 UnionEntry &En = Unions[Parent];
3059 if (En.first && En.first != Child) {
3060 S.Diag(Init->getSourceLocation(),
3061 diag::err_multiple_mem_union_initialization)
3062 << Field->getDeclName()
3063 << Init->getSourceRange();
3064 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3065 << 0 << En.second->getSourceRange();
3066 return true;
3067 } else if (!En.first) {
3068 En.first = Child;
3069 En.second = Init;
3070 }
3071 }
3072
3073 Child = Parent;
3074 Parent = cast<RecordDecl>(Parent->getDeclContext());
3075 } while (Parent->isAnonymousStructOrUnion());
3076
3077 return false;
3078}
3079}
3080
Anders Carlssone857b292010-04-02 03:37:03 +00003081/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003082void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003083 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00003084 CXXCtorInitializer **meminits,
3085 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003086 bool AnyErrors) {
3087 if (!ConstructorDecl)
3088 return;
3089
3090 AdjustDeclIfTemplate(ConstructorDecl);
3091
3092 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003093 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003094
3095 if (!Constructor) {
3096 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3097 return;
3098 }
3099
Alexis Hunt1d792652011-01-08 20:30:50 +00003100 CXXCtorInitializer **MemInits =
3101 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00003102
3103 // Mapping for the duplicate initializers check.
3104 // For member initializers, this is keyed with a FieldDecl*.
3105 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003106 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003107
3108 // Mapping for the inconsistent anonymous-union initializers check.
3109 RedundantUnionMap MemberUnions;
3110
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003111 bool HadError = false;
3112 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003113 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003114
Abramo Bagnara341d7832010-05-26 18:09:23 +00003115 // Set the source order index.
3116 Init->setSourceOrder(i);
3117
Francois Pichetd583da02010-12-04 09:14:42 +00003118 if (Init->isAnyMemberInitializer()) {
3119 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003120 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3121 CheckRedundantUnionInit(*this, Init, MemberUnions))
3122 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003123 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003124 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3125 if (CheckRedundantInit(*this, Init, Members[Key]))
3126 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003127 } else {
3128 assert(Init->isDelegatingInitializer());
3129 // This must be the only initializer
3130 if (i != 0 || NumMemInits > 1) {
3131 Diag(MemInits[0]->getSourceLocation(),
3132 diag::err_delegating_initializer_alone)
3133 << MemInits[0]->getSourceRange();
3134 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00003135 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003136 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003137 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003138 // Return immediately as the initializer is set.
3139 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003140 }
Anders Carlssone857b292010-04-02 03:37:03 +00003141 }
3142
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003143 if (HadError)
3144 return;
3145
Anders Carlssone857b292010-04-02 03:37:03 +00003146 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003147
Alexis Hunt1d792652011-01-08 20:30:50 +00003148 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00003149}
3150
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003151void
John McCalla6309952010-03-16 21:39:52 +00003152Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3153 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003154 // Ignore dependent contexts. Also ignore unions, since their members never
3155 // have destructors implicitly called.
3156 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003157 return;
John McCall1064d7e2010-03-16 05:22:47 +00003158
3159 // FIXME: all the access-control diagnostics are positioned on the
3160 // field/base declaration. That's probably good; that said, the
3161 // user might reasonably want to know why the destructor is being
3162 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003163
Anders Carlssondee9a302009-11-17 04:44:12 +00003164 // Non-static data members.
3165 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3166 E = ClassDecl->field_end(); I != E; ++I) {
3167 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003168 if (Field->isInvalidDecl())
3169 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003170 QualType FieldType = Context.getBaseElementType(Field->getType());
3171
3172 const RecordType* RT = FieldType->getAs<RecordType>();
3173 if (!RT)
3174 continue;
3175
3176 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003177 if (FieldClassDecl->isInvalidDecl())
3178 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003179 if (FieldClassDecl->hasTrivialDestructor())
3180 continue;
3181
Douglas Gregore71edda2010-07-01 22:47:18 +00003182 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003183 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003184 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003185 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003186 << Field->getDeclName()
3187 << FieldType);
3188
John McCalla6309952010-03-16 21:39:52 +00003189 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003190 }
3191
John McCall1064d7e2010-03-16 05:22:47 +00003192 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3193
Anders Carlssondee9a302009-11-17 04:44:12 +00003194 // Bases.
3195 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3196 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003197 // Bases are always records in a well-formed non-dependent class.
3198 const RecordType *RT = Base->getType()->getAs<RecordType>();
3199
3200 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003201 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003202 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003203
John McCall1064d7e2010-03-16 05:22:47 +00003204 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003205 // If our base class is invalid, we probably can't get its dtor anyway.
3206 if (BaseClassDecl->isInvalidDecl())
3207 continue;
3208 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00003209 if (BaseClassDecl->hasTrivialDestructor())
3210 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003211
Douglas Gregore71edda2010-07-01 22:47:18 +00003212 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003213 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003214
3215 // FIXME: caret should be on the start of the class name
3216 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003217 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003218 << Base->getType()
3219 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00003220
John McCalla6309952010-03-16 21:39:52 +00003221 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003222 }
3223
3224 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003225 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3226 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003227
3228 // Bases are always records in a well-formed non-dependent class.
3229 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3230
3231 // Ignore direct virtual bases.
3232 if (DirectVirtualBases.count(RT))
3233 continue;
3234
John McCall1064d7e2010-03-16 05:22:47 +00003235 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003236 // If our base class is invalid, we probably can't get its dtor anyway.
3237 if (BaseClassDecl->isInvalidDecl())
3238 continue;
3239 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003240 if (BaseClassDecl->hasTrivialDestructor())
3241 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003242
Douglas Gregore71edda2010-07-01 22:47:18 +00003243 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003244 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003245 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003246 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00003247 << VBase->getType());
3248
John McCalla6309952010-03-16 21:39:52 +00003249 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003250 }
3251}
3252
John McCall48871652010-08-21 09:40:31 +00003253void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003254 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003255 return;
Mike Stump11289f42009-09-09 15:08:12 +00003256
Mike Stump11289f42009-09-09 15:08:12 +00003257 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003258 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00003259 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003260}
3261
Mike Stump11289f42009-09-09 15:08:12 +00003262bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003263 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00003264 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00003265 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00003266 else
John McCall02db245d2010-08-18 09:41:07 +00003267 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00003268}
3269
Anders Carlssoneabf7702009-08-27 00:13:57 +00003270bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003271 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003272 if (!getLangOptions().CPlusPlus)
3273 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003274
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003275 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00003276 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00003277
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003278 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003279 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003280 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003281 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003282
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003283 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00003284 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003285 }
Mike Stump11289f42009-09-09 15:08:12 +00003286
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003287 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003288 if (!RT)
3289 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003290
John McCall67da35c2010-02-04 22:26:26 +00003291 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003292
John McCall02db245d2010-08-18 09:41:07 +00003293 // We can't answer whether something is abstract until it has a
3294 // definition. If it's currently being defined, we'll walk back
3295 // over all the declarations when we have a full definition.
3296 const CXXRecordDecl *Def = RD->getDefinition();
3297 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003298 return false;
3299
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003300 if (!RD->isAbstract())
3301 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003302
Anders Carlssoneabf7702009-08-27 00:13:57 +00003303 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00003304 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003305
John McCall02db245d2010-08-18 09:41:07 +00003306 return true;
3307}
3308
3309void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3310 // Check if we've already emitted the list of pure virtual functions
3311 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003312 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003313 return;
Mike Stump11289f42009-09-09 15:08:12 +00003314
Douglas Gregor4165bd62010-03-23 23:47:56 +00003315 CXXFinalOverriderMap FinalOverriders;
3316 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003317
Anders Carlssona2f74f32010-06-03 01:00:02 +00003318 // Keep a set of seen pure methods so we won't diagnose the same method
3319 // more than once.
3320 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3321
Douglas Gregor4165bd62010-03-23 23:47:56 +00003322 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3323 MEnd = FinalOverriders.end();
3324 M != MEnd;
3325 ++M) {
3326 for (OverridingMethods::iterator SO = M->second.begin(),
3327 SOEnd = M->second.end();
3328 SO != SOEnd; ++SO) {
3329 // C++ [class.abstract]p4:
3330 // A class is abstract if it contains or inherits at least one
3331 // pure virtual function for which the final overrider is pure
3332 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003333
Douglas Gregor4165bd62010-03-23 23:47:56 +00003334 //
3335 if (SO->second.size() != 1)
3336 continue;
3337
3338 if (!SO->second.front().Method->isPure())
3339 continue;
3340
Anders Carlssona2f74f32010-06-03 01:00:02 +00003341 if (!SeenPureMethods.insert(SO->second.front().Method))
3342 continue;
3343
Douglas Gregor4165bd62010-03-23 23:47:56 +00003344 Diag(SO->second.front().Method->getLocation(),
3345 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003346 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003347 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003348 }
3349
3350 if (!PureVirtualClassDiagSet)
3351 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3352 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003353}
3354
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003355namespace {
John McCall02db245d2010-08-18 09:41:07 +00003356struct AbstractUsageInfo {
3357 Sema &S;
3358 CXXRecordDecl *Record;
3359 CanQualType AbstractType;
3360 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003361
John McCall02db245d2010-08-18 09:41:07 +00003362 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3363 : S(S), Record(Record),
3364 AbstractType(S.Context.getCanonicalType(
3365 S.Context.getTypeDeclType(Record))),
3366 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003367
John McCall02db245d2010-08-18 09:41:07 +00003368 void DiagnoseAbstractType() {
3369 if (Invalid) return;
3370 S.DiagnoseAbstractType(Record);
3371 Invalid = true;
3372 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003373
John McCall02db245d2010-08-18 09:41:07 +00003374 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3375};
3376
3377struct CheckAbstractUsage {
3378 AbstractUsageInfo &Info;
3379 const NamedDecl *Ctx;
3380
3381 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3382 : Info(Info), Ctx(Ctx) {}
3383
3384 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3385 switch (TL.getTypeLocClass()) {
3386#define ABSTRACT_TYPELOC(CLASS, PARENT)
3387#define TYPELOC(CLASS, PARENT) \
3388 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3389#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003390 }
John McCall02db245d2010-08-18 09:41:07 +00003391 }
Mike Stump11289f42009-09-09 15:08:12 +00003392
John McCall02db245d2010-08-18 09:41:07 +00003393 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3394 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3395 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003396 if (!TL.getArg(I))
3397 continue;
3398
John McCall02db245d2010-08-18 09:41:07 +00003399 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3400 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003401 }
John McCall02db245d2010-08-18 09:41:07 +00003402 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003403
John McCall02db245d2010-08-18 09:41:07 +00003404 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3405 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3406 }
Mike Stump11289f42009-09-09 15:08:12 +00003407
John McCall02db245d2010-08-18 09:41:07 +00003408 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3409 // Visit the type parameters from a permissive context.
3410 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3411 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3412 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3413 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3414 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3415 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003416 }
John McCall02db245d2010-08-18 09:41:07 +00003417 }
Mike Stump11289f42009-09-09 15:08:12 +00003418
John McCall02db245d2010-08-18 09:41:07 +00003419 // Visit pointee types from a permissive context.
3420#define CheckPolymorphic(Type) \
3421 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3422 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3423 }
3424 CheckPolymorphic(PointerTypeLoc)
3425 CheckPolymorphic(ReferenceTypeLoc)
3426 CheckPolymorphic(MemberPointerTypeLoc)
3427 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00003428 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003429
John McCall02db245d2010-08-18 09:41:07 +00003430 /// Handle all the types we haven't given a more specific
3431 /// implementation for above.
3432 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3433 // Every other kind of type that we haven't called out already
3434 // that has an inner type is either (1) sugar or (2) contains that
3435 // inner type in some way as a subobject.
3436 if (TypeLoc Next = TL.getNextTypeLoc())
3437 return Visit(Next, Sel);
3438
3439 // If there's no inner type and we're in a permissive context,
3440 // don't diagnose.
3441 if (Sel == Sema::AbstractNone) return;
3442
3443 // Check whether the type matches the abstract type.
3444 QualType T = TL.getType();
3445 if (T->isArrayType()) {
3446 Sel = Sema::AbstractArrayType;
3447 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003448 }
John McCall02db245d2010-08-18 09:41:07 +00003449 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3450 if (CT != Info.AbstractType) return;
3451
3452 // It matched; do some magic.
3453 if (Sel == Sema::AbstractArrayType) {
3454 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3455 << T << TL.getSourceRange();
3456 } else {
3457 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3458 << Sel << T << TL.getSourceRange();
3459 }
3460 Info.DiagnoseAbstractType();
3461 }
3462};
3463
3464void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3465 Sema::AbstractDiagSelID Sel) {
3466 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3467}
3468
3469}
3470
3471/// Check for invalid uses of an abstract type in a method declaration.
3472static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3473 CXXMethodDecl *MD) {
3474 // No need to do the check on definitions, which require that
3475 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003476 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003477 return;
3478
3479 // For safety's sake, just ignore it if we don't have type source
3480 // information. This should never happen for non-implicit methods,
3481 // but...
3482 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3483 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3484}
3485
3486/// Check for invalid uses of an abstract type within a class definition.
3487static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3488 CXXRecordDecl *RD) {
3489 for (CXXRecordDecl::decl_iterator
3490 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3491 Decl *D = *I;
3492 if (D->isImplicit()) continue;
3493
3494 // Methods and method templates.
3495 if (isa<CXXMethodDecl>(D)) {
3496 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3497 } else if (isa<FunctionTemplateDecl>(D)) {
3498 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3499 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3500
3501 // Fields and static variables.
3502 } else if (isa<FieldDecl>(D)) {
3503 FieldDecl *FD = cast<FieldDecl>(D);
3504 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3505 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3506 } else if (isa<VarDecl>(D)) {
3507 VarDecl *VD = cast<VarDecl>(D);
3508 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3509 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3510
3511 // Nested classes and class templates.
3512 } else if (isa<CXXRecordDecl>(D)) {
3513 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3514 } else if (isa<ClassTemplateDecl>(D)) {
3515 CheckAbstractClassUsage(Info,
3516 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3517 }
3518 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003519}
3520
Douglas Gregorc99f1552009-12-03 18:33:45 +00003521/// \brief Perform semantic checks on a class definition that has been
3522/// completing, introducing implicitly-declared members, checking for
3523/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003524void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003525 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003526 return;
3527
John McCall02db245d2010-08-18 09:41:07 +00003528 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3529 AbstractUsageInfo Info(*this, Record);
3530 CheckAbstractClassUsage(Info, Record);
3531 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003532
3533 // If this is not an aggregate type and has no user-declared constructor,
3534 // complain about any non-static data members of reference or const scalar
3535 // type, since they will never get initializers.
3536 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3537 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3538 bool Complained = false;
3539 for (RecordDecl::field_iterator F = Record->field_begin(),
3540 FEnd = Record->field_end();
3541 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003542 if (F->hasInClassInitializer())
3543 continue;
3544
Douglas Gregor454a5b62010-04-15 00:00:53 +00003545 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003546 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003547 if (!Complained) {
3548 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3549 << Record->getTagKind() << Record;
3550 Complained = true;
3551 }
3552
3553 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3554 << F->getType()->isReferenceType()
3555 << F->getDeclName();
3556 }
3557 }
3558 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003559
Anders Carlssone771e762011-01-25 18:08:22 +00003560 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003561 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003562
3563 if (Record->getIdentifier()) {
3564 // C++ [class.mem]p13:
3565 // If T is the name of a class, then each of the following shall have a
3566 // name different from T:
3567 // - every member of every anonymous union that is a member of class T.
3568 //
3569 // C++ [class.mem]p14:
3570 // In addition, if class T has a user-declared constructor (12.1), every
3571 // non-static data member of class T shall have a name different from T.
3572 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003573 R.first != R.second; ++R.first) {
3574 NamedDecl *D = *R.first;
3575 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3576 isa<IndirectFieldDecl>(D)) {
3577 Diag(D->getLocation(), diag::err_member_name_of_class)
3578 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003579 break;
3580 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003581 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003582 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003583
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003584 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003585 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003586 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003587 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003588 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3589 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3590 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003591
3592 // See if a method overloads virtual methods in a base
3593 /// class without overriding any.
3594 if (!Record->isDependentType()) {
3595 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3596 MEnd = Record->method_end();
3597 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003598 if (!(*M)->isStatic())
3599 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003600 }
3601 }
Sebastian Redl08905022011-02-05 19:23:19 +00003602
Richard Smitheb3c10c2011-10-01 02:31:28 +00003603 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3604 // function that is not a constructor declares that member function to be
3605 // const. [...] The class of which that function is a member shall be
3606 // a literal type.
3607 //
3608 // It's fine to diagnose constructors here too: such constructors cannot
3609 // produce a constant expression, so are ill-formed (no diagnostic required).
3610 //
3611 // If the class has virtual bases, any constexpr members will already have
3612 // been diagnosed by the checks performed on the member declaration, so
3613 // suppress this (less useful) diagnostic.
3614 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3615 !Record->isLiteral() && !Record->getNumVBases()) {
3616 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3617 MEnd = Record->method_end();
3618 M != MEnd; ++M) {
3619 if ((*M)->isConstexpr()) {
3620 switch (Record->getTemplateSpecializationKind()) {
3621 case TSK_ImplicitInstantiation:
3622 case TSK_ExplicitInstantiationDeclaration:
3623 case TSK_ExplicitInstantiationDefinition:
3624 // If a template instantiates to a non-literal type, but its members
3625 // instantiate to constexpr functions, the template is technically
3626 // ill-formed, but we allow it for sanity. Such members are treated as
3627 // non-constexpr.
3628 (*M)->setConstexpr(false);
3629 continue;
3630
3631 case TSK_Undeclared:
3632 case TSK_ExplicitSpecialization:
3633 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3634 PDiag(diag::err_constexpr_method_non_literal));
3635 break;
3636 }
3637
3638 // Only produce one error per class.
3639 break;
3640 }
3641 }
3642 }
3643
Sebastian Redl08905022011-02-05 19:23:19 +00003644 // Declare inherited constructors. We do this eagerly here because:
3645 // - The standard requires an eager diagnostic for conflicting inherited
3646 // constructors from different classes.
3647 // - The lazy declaration of the other implicit constructors is so as to not
3648 // waste space and performance on classes that are not meant to be
3649 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3650 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003651 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003652
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003653 if (!Record->isDependentType())
3654 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003655}
3656
3657void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003658 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3659 ME = Record->method_end();
3660 MI != ME; ++MI) {
3661 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3662 switch (getSpecialMember(*MI)) {
3663 case CXXDefaultConstructor:
3664 CheckExplicitlyDefaultedDefaultConstructor(
3665 cast<CXXConstructorDecl>(*MI));
3666 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003667
Alexis Huntf91729462011-05-12 22:46:25 +00003668 case CXXDestructor:
3669 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3670 break;
3671
3672 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003673 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3674 break;
3675
Alexis Huntf91729462011-05-12 22:46:25 +00003676 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003677 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003678 break;
3679
Alexis Hunt119c10e2011-05-25 23:16:36 +00003680 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003681 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003682 break;
3683
Sebastian Redl22653ba2011-08-30 19:58:05 +00003684 case CXXMoveAssignment:
3685 CheckExplicitlyDefaultedMoveAssignment(*MI);
3686 break;
3687
3688 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003689 llvm_unreachable("non-special member explicitly defaulted!");
3690 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003691 }
3692 }
3693
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003694}
3695
3696void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3697 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3698
3699 // Whether this was the first-declared instance of the constructor.
3700 // This affects whether we implicitly add an exception spec (and, eventually,
3701 // constexpr). It is also ill-formed to explicitly default a constructor such
3702 // that it would be deleted. (C++0x [decl.fct.def.default])
3703 bool First = CD == CD->getCanonicalDecl();
3704
Alexis Hunt913820d2011-05-13 06:10:58 +00003705 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003706 if (CD->getNumParams() != 0) {
3707 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3708 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003709 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003710 }
3711
3712 ImplicitExceptionSpecification Spec
3713 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3714 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003715 if (EPI.ExceptionSpecType == EST_Delayed) {
3716 // Exception specification depends on some deferred part of the class. We'll
3717 // try again when the class's definition has been fully processed.
3718 return;
3719 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003720 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3721 *ExceptionType = Context.getFunctionType(
3722 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3723
3724 if (CtorType->hasExceptionSpec()) {
3725 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003726 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003727 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003728 PDiag(),
3729 ExceptionType, SourceLocation(),
3730 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003731 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003732 }
3733 } else if (First) {
3734 // We set the declaration to have the computed exception spec here.
3735 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003736 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003737 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3738 }
Alexis Huntb3153022011-05-12 03:51:48 +00003739
Alexis Hunt913820d2011-05-13 06:10:58 +00003740 if (HadError) {
3741 CD->setInvalidDecl();
3742 return;
3743 }
3744
Alexis Huntb3153022011-05-12 03:51:48 +00003745 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003746 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003747 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003748 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003749 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003750 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003751 CD->setInvalidDecl();
3752 }
3753 }
3754}
3755
3756void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3757 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3758
3759 // Whether this was the first-declared instance of the constructor.
3760 bool First = CD == CD->getCanonicalDecl();
3761
3762 bool HadError = false;
3763 if (CD->getNumParams() != 1) {
3764 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3765 << CD->getSourceRange();
3766 HadError = true;
3767 }
3768
3769 ImplicitExceptionSpecification Spec(Context);
3770 bool Const;
3771 llvm::tie(Spec, Const) =
3772 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3773
3774 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3775 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3776 *ExceptionType = Context.getFunctionType(
3777 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3778
3779 // Check for parameter type matching.
3780 // This is a copy ctor so we know it's a cv-qualified reference to T.
3781 QualType ArgType = CtorType->getArgType(0);
3782 if (ArgType->getPointeeType().isVolatileQualified()) {
3783 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3784 HadError = true;
3785 }
3786 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3787 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3788 HadError = true;
3789 }
3790
3791 if (CtorType->hasExceptionSpec()) {
3792 if (CheckEquivalentExceptionSpec(
3793 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003794 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003795 PDiag(),
3796 ExceptionType, SourceLocation(),
3797 CtorType, CD->getLocation())) {
3798 HadError = true;
3799 }
3800 } else if (First) {
3801 // We set the declaration to have the computed exception spec here.
3802 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003803 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003804 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3805 }
3806
3807 if (HadError) {
3808 CD->setInvalidDecl();
3809 return;
3810 }
3811
3812 if (ShouldDeleteCopyConstructor(CD)) {
3813 if (First) {
3814 CD->setDeletedAsWritten();
3815 } else {
3816 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003817 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003818 CD->setInvalidDecl();
3819 }
Alexis Huntb3153022011-05-12 03:51:48 +00003820 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003821}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003822
Alexis Huntc9a55732011-05-14 05:23:28 +00003823void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3824 assert(MD->isExplicitlyDefaulted());
3825
3826 // Whether this was the first-declared instance of the operator
3827 bool First = MD == MD->getCanonicalDecl();
3828
3829 bool HadError = false;
3830 if (MD->getNumParams() != 1) {
3831 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3832 << MD->getSourceRange();
3833 HadError = true;
3834 }
3835
3836 QualType ReturnType =
3837 MD->getType()->getAs<FunctionType>()->getResultType();
3838 if (!ReturnType->isLValueReferenceType() ||
3839 !Context.hasSameType(
3840 Context.getCanonicalType(ReturnType->getPointeeType()),
3841 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3842 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3843 HadError = true;
3844 }
3845
3846 ImplicitExceptionSpecification Spec(Context);
3847 bool Const;
3848 llvm::tie(Spec, Const) =
3849 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3850
3851 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3852 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3853 *ExceptionType = Context.getFunctionType(
3854 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3855
Alexis Huntc9a55732011-05-14 05:23:28 +00003856 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003857 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00003858 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003859 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003860 } else {
3861 if (ArgType->getPointeeType().isVolatileQualified()) {
3862 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3863 HadError = true;
3864 }
3865 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3866 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3867 HadError = true;
3868 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003869 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003870
Alexis Huntc9a55732011-05-14 05:23:28 +00003871 if (OperType->getTypeQuals()) {
3872 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3873 HadError = true;
3874 }
3875
3876 if (OperType->hasExceptionSpec()) {
3877 if (CheckEquivalentExceptionSpec(
3878 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003879 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003880 PDiag(),
3881 ExceptionType, SourceLocation(),
3882 OperType, MD->getLocation())) {
3883 HadError = true;
3884 }
3885 } else if (First) {
3886 // We set the declaration to have the computed exception spec here.
3887 // We duplicate the one parameter type.
3888 EPI.RefQualifier = OperType->getRefQualifier();
3889 EPI.ExtInfo = OperType->getExtInfo();
3890 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3891 }
3892
3893 if (HadError) {
3894 MD->setInvalidDecl();
3895 return;
3896 }
3897
3898 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3899 if (First) {
3900 MD->setDeletedAsWritten();
3901 } else {
3902 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003903 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003904 MD->setInvalidDecl();
3905 }
3906 }
3907}
3908
Sebastian Redl22653ba2011-08-30 19:58:05 +00003909void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3910 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3911
3912 // Whether this was the first-declared instance of the constructor.
3913 bool First = CD == CD->getCanonicalDecl();
3914
3915 bool HadError = false;
3916 if (CD->getNumParams() != 1) {
3917 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3918 << CD->getSourceRange();
3919 HadError = true;
3920 }
3921
3922 ImplicitExceptionSpecification Spec(
3923 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3924
3925 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3926 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3927 *ExceptionType = Context.getFunctionType(
3928 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3929
3930 // Check for parameter type matching.
3931 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3932 QualType ArgType = CtorType->getArgType(0);
3933 if (ArgType->getPointeeType().isVolatileQualified()) {
3934 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3935 HadError = true;
3936 }
3937 if (ArgType->getPointeeType().isConstQualified()) {
3938 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3939 HadError = true;
3940 }
3941
3942 if (CtorType->hasExceptionSpec()) {
3943 if (CheckEquivalentExceptionSpec(
3944 PDiag(diag::err_incorrect_defaulted_exception_spec)
3945 << CXXMoveConstructor,
3946 PDiag(),
3947 ExceptionType, SourceLocation(),
3948 CtorType, CD->getLocation())) {
3949 HadError = true;
3950 }
3951 } else if (First) {
3952 // We set the declaration to have the computed exception spec here.
3953 // We duplicate the one parameter type.
3954 EPI.ExtInfo = CtorType->getExtInfo();
3955 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3956 }
3957
3958 if (HadError) {
3959 CD->setInvalidDecl();
3960 return;
3961 }
3962
3963 if (ShouldDeleteMoveConstructor(CD)) {
3964 if (First) {
3965 CD->setDeletedAsWritten();
3966 } else {
3967 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3968 << CXXMoveConstructor;
3969 CD->setInvalidDecl();
3970 }
3971 }
3972}
3973
3974void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3975 assert(MD->isExplicitlyDefaulted());
3976
3977 // Whether this was the first-declared instance of the operator
3978 bool First = MD == MD->getCanonicalDecl();
3979
3980 bool HadError = false;
3981 if (MD->getNumParams() != 1) {
3982 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3983 << MD->getSourceRange();
3984 HadError = true;
3985 }
3986
3987 QualType ReturnType =
3988 MD->getType()->getAs<FunctionType>()->getResultType();
3989 if (!ReturnType->isLValueReferenceType() ||
3990 !Context.hasSameType(
3991 Context.getCanonicalType(ReturnType->getPointeeType()),
3992 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3993 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3994 HadError = true;
3995 }
3996
3997 ImplicitExceptionSpecification Spec(
3998 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3999
4000 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4001 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4002 *ExceptionType = Context.getFunctionType(
4003 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4004
4005 QualType ArgType = OperType->getArgType(0);
4006 if (!ArgType->isRValueReferenceType()) {
4007 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4008 HadError = true;
4009 } else {
4010 if (ArgType->getPointeeType().isVolatileQualified()) {
4011 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4012 HadError = true;
4013 }
4014 if (ArgType->getPointeeType().isConstQualified()) {
4015 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4016 HadError = true;
4017 }
4018 }
4019
4020 if (OperType->getTypeQuals()) {
4021 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4022 HadError = true;
4023 }
4024
4025 if (OperType->hasExceptionSpec()) {
4026 if (CheckEquivalentExceptionSpec(
4027 PDiag(diag::err_incorrect_defaulted_exception_spec)
4028 << CXXMoveAssignment,
4029 PDiag(),
4030 ExceptionType, SourceLocation(),
4031 OperType, MD->getLocation())) {
4032 HadError = true;
4033 }
4034 } else if (First) {
4035 // We set the declaration to have the computed exception spec here.
4036 // We duplicate the one parameter type.
4037 EPI.RefQualifier = OperType->getRefQualifier();
4038 EPI.ExtInfo = OperType->getExtInfo();
4039 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4040 }
4041
4042 if (HadError) {
4043 MD->setInvalidDecl();
4044 return;
4045 }
4046
4047 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4048 if (First) {
4049 MD->setDeletedAsWritten();
4050 } else {
4051 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4052 << CXXMoveAssignment;
4053 MD->setInvalidDecl();
4054 }
4055 }
4056}
4057
Alexis Huntf91729462011-05-12 22:46:25 +00004058void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4059 assert(DD->isExplicitlyDefaulted());
4060
4061 // Whether this was the first-declared instance of the destructor.
4062 bool First = DD == DD->getCanonicalDecl();
4063
4064 ImplicitExceptionSpecification Spec
4065 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4066 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4067 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4068 *ExceptionType = Context.getFunctionType(
4069 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4070
4071 if (DtorType->hasExceptionSpec()) {
4072 if (CheckEquivalentExceptionSpec(
4073 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004074 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00004075 PDiag(),
4076 ExceptionType, SourceLocation(),
4077 DtorType, DD->getLocation())) {
4078 DD->setInvalidDecl();
4079 return;
4080 }
4081 } else if (First) {
4082 // We set the declaration to have the computed exception spec here.
4083 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00004084 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00004085 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4086 }
4087
4088 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00004089 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004090 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00004091 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00004092 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004093 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00004094 DD->setInvalidDecl();
4095 }
Alexis Huntf91729462011-05-12 22:46:25 +00004096 }
Alexis Huntf91729462011-05-12 22:46:25 +00004097}
4098
Alexis Huntea6f0322011-05-11 22:34:38 +00004099bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
4100 CXXRecordDecl *RD = CD->getParent();
4101 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004102 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004103 return false;
4104
Alexis Hunte77a28f2011-05-18 03:41:58 +00004105 SourceLocation Loc = CD->getLocation();
4106
Alexis Huntea6f0322011-05-11 22:34:38 +00004107 // Do access control from the constructor
4108 ContextRAII CtorContext(*this, CD);
4109
4110 bool Union = RD->isUnion();
4111 bool AllConst = true;
4112
Alexis Huntea6f0322011-05-11 22:34:38 +00004113 // We do this because we should never actually use an anonymous
4114 // union's constructor.
4115 if (Union && RD->isAnonymousStructOrUnion())
4116 return false;
4117
4118 // FIXME: We should put some diagnostic logic right into this function.
4119
4120 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00004121 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00004122
4123 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4124 BE = RD->bases_end();
4125 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00004126 // We'll handle this one later
4127 if (BI->isVirtual())
4128 continue;
4129
Alexis Huntea6f0322011-05-11 22:34:38 +00004130 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4131 assert(BaseDecl && "base isn't a CXXRecordDecl");
4132
4133 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00004134 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00004135 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4136 if (BaseDtor->isDeleted())
4137 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004138 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00004139 AR_accessible)
4140 return true;
4141
Alexis Huntea6f0322011-05-11 22:34:38 +00004142 // -- any [direct base class either] has no default constructor or
4143 // overload resolution as applied to [its] default constructor
4144 // results in an ambiguity or in a function that is deleted or
4145 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00004146 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
4147 if (!BaseDefault || BaseDefault->isDeleted())
4148 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004149
Alexis Hunteef8ee02011-06-10 03:50:41 +00004150 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
4151 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00004152 return true;
4153 }
4154
4155 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4156 BE = RD->vbases_end();
4157 BI != BE; ++BI) {
4158 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4159 assert(BaseDecl && "base isn't a CXXRecordDecl");
4160
4161 // -- any [virtual base class] has a type with a destructor that is
4162 // delete or inaccessible from the defaulted default constructor
4163 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4164 if (BaseDtor->isDeleted())
4165 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004166 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00004167 AR_accessible)
4168 return true;
4169
4170 // -- any [virtual base class either] has no default constructor or
4171 // overload resolution as applied to [its] default constructor
4172 // results in an ambiguity or in a function that is deleted or
4173 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00004174 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
4175 if (!BaseDefault || BaseDefault->isDeleted())
4176 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004177
Alexis Hunteef8ee02011-06-10 03:50:41 +00004178 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
4179 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00004180 return true;
4181 }
4182
4183 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4184 FE = RD->field_end();
4185 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00004186 if (FI->isInvalidDecl())
4187 continue;
4188
Alexis Huntea6f0322011-05-11 22:34:38 +00004189 QualType FieldType = Context.getBaseElementType(FI->getType());
4190 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00004191
Alexis Huntea6f0322011-05-11 22:34:38 +00004192 // -- any non-static data member with no brace-or-equal-initializer is of
4193 // reference type
Richard Smith938f40b2011-06-11 17:19:42 +00004194 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Alexis Huntea6f0322011-05-11 22:34:38 +00004195 return true;
4196
4197 // -- X is a union and all its variant members are of const-qualified type
4198 // (or array thereof)
4199 if (Union && !FieldType.isConstQualified())
4200 AllConst = false;
4201
4202 if (FieldRecord) {
4203 // -- X is a union-like class that has a variant member with a non-trivial
4204 // default constructor
4205 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
4206 return true;
4207
4208 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4209 if (FieldDtor->isDeleted())
4210 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004211 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00004212 AR_accessible)
4213 return true;
4214
4215 // -- any non-variant non-static data member of const-qualified type (or
4216 // array thereof) with no brace-or-equal-initializer does not have a
4217 // user-provided default constructor
4218 if (FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00004219 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004220 !FieldRecord->hasUserProvidedDefaultConstructor())
4221 return true;
4222
4223 if (!Union && FieldRecord->isUnion() &&
4224 FieldRecord->isAnonymousStructOrUnion()) {
4225 // We're okay to reuse AllConst here since we only care about the
4226 // value otherwise if we're in a union.
4227 AllConst = true;
4228
4229 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4230 UE = FieldRecord->field_end();
4231 UI != UE; ++UI) {
4232 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4233 CXXRecordDecl *UnionFieldRecord =
4234 UnionFieldType->getAsCXXRecordDecl();
4235
4236 if (!UnionFieldType.isConstQualified())
4237 AllConst = false;
4238
4239 if (UnionFieldRecord &&
4240 !UnionFieldRecord->hasTrivialDefaultConstructor())
4241 return true;
4242 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00004243
Alexis Huntea6f0322011-05-11 22:34:38 +00004244 if (AllConst)
4245 return true;
4246
4247 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00004248 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00004249 continue;
4250 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00004251
Richard Smith938f40b2011-06-11 17:19:42 +00004252 // -- any non-static data member with no brace-or-equal-initializer has
4253 // class type M (or array thereof) and either M has no default
4254 // constructor or overload resolution as applied to M's default
4255 // constructor results in an ambiguity or in a function that is deleted
4256 // or inaccessible from the defaulted default constructor.
4257 if (!FI->hasInClassInitializer()) {
4258 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
4259 if (!FieldDefault || FieldDefault->isDeleted())
4260 return true;
4261 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
4262 PDiag()) != AR_accessible)
4263 return true;
4264 }
4265 } else if (!Union && FieldType.isConstQualified() &&
4266 !FI->hasInClassInitializer()) {
Alexis Hunta671bca2011-05-20 21:43:47 +00004267 // -- any non-variant non-static data member of const-qualified type (or
4268 // array thereof) with no brace-or-equal-initializer does not have a
4269 // user-provided default constructor
4270 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004271 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004272 }
4273
4274 if (Union && AllConst)
4275 return true;
4276
4277 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004278}
4279
Alexis Hunt913820d2011-05-13 06:10:58 +00004280bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00004281 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00004282 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004283 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Hunt913820d2011-05-13 06:10:58 +00004284 return false;
4285
Alexis Hunte77a28f2011-05-18 03:41:58 +00004286 SourceLocation Loc = CD->getLocation();
4287
Alexis Hunt913820d2011-05-13 06:10:58 +00004288 // Do access control from the constructor
4289 ContextRAII CtorContext(*this, CD);
4290
Alexis Hunt899bd442011-06-10 04:44:37 +00004291 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00004292
Alexis Huntc9a55732011-05-14 05:23:28 +00004293 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4294 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00004295 unsigned ArgQuals =
4296 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4297 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00004298
4299 // We do this because we should never actually use an anonymous
4300 // union's constructor.
4301 if (Union && RD->isAnonymousStructOrUnion())
4302 return false;
4303
4304 // FIXME: We should put some diagnostic logic right into this function.
4305
4306 // C++0x [class.copy]/11
4307 // A defaulted [copy] constructor for class X is defined as delete if X has:
4308
4309 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4310 BE = RD->bases_end();
4311 BI != BE; ++BI) {
4312 // We'll handle this one later
4313 if (BI->isVirtual())
4314 continue;
4315
4316 QualType BaseType = BI->getType();
4317 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4318 assert(BaseDecl && "base isn't a CXXRecordDecl");
4319
4320 // -- any [direct base class] of a type with a destructor that is deleted or
4321 // inaccessible from the defaulted constructor
4322 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4323 if (BaseDtor->isDeleted())
4324 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004325 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00004326 AR_accessible)
4327 return true;
4328
4329 // -- a [direct base class] B that cannot be [copied] because overload
4330 // resolution, as applied to B's [copy] constructor, results in an
4331 // ambiguity or a function that is deleted or inaccessible from the
4332 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00004333 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004334 if (!BaseCtor || BaseCtor->isDeleted())
4335 return true;
4336 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4337 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00004338 return true;
4339 }
4340
4341 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4342 BE = RD->vbases_end();
4343 BI != BE; ++BI) {
4344 QualType BaseType = BI->getType();
4345 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4346 assert(BaseDecl && "base isn't a CXXRecordDecl");
4347
Alexis Hunteef8ee02011-06-10 03:50:41 +00004348 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00004349 // inaccessible from the defaulted constructor
4350 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4351 if (BaseDtor->isDeleted())
4352 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004353 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00004354 AR_accessible)
4355 return true;
4356
4357 // -- a [virtual base class] B that cannot be [copied] because overload
4358 // resolution, as applied to B's [copy] constructor, results in an
4359 // ambiguity or a function that is deleted or inaccessible from the
4360 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00004361 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004362 if (!BaseCtor || BaseCtor->isDeleted())
4363 return true;
4364 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4365 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00004366 return true;
4367 }
4368
4369 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4370 FE = RD->field_end();
4371 FI != FE; ++FI) {
4372 QualType FieldType = Context.getBaseElementType(FI->getType());
4373
4374 // -- for a copy constructor, a non-static data member of rvalue reference
4375 // type
4376 if (FieldType->isRValueReferenceType())
4377 return true;
4378
4379 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4380
4381 if (FieldRecord) {
4382 // This is an anonymous union
4383 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4384 // Anonymous unions inside unions do not variant members create
4385 if (!Union) {
4386 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4387 UE = FieldRecord->field_end();
4388 UI != UE; ++UI) {
4389 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4390 CXXRecordDecl *UnionFieldRecord =
4391 UnionFieldType->getAsCXXRecordDecl();
4392
4393 // -- a variant member with a non-trivial [copy] constructor and X
4394 // is a union-like class
4395 if (UnionFieldRecord &&
4396 !UnionFieldRecord->hasTrivialCopyConstructor())
4397 return true;
4398 }
4399 }
4400
4401 // Don't try to initalize an anonymous union
4402 continue;
4403 } else {
4404 // -- a variant member with a non-trivial [copy] constructor and X is a
4405 // union-like class
4406 if (Union && !FieldRecord->hasTrivialCopyConstructor())
4407 return true;
4408
4409 // -- any [non-static data member] of a type with a destructor that is
4410 // deleted or inaccessible from the defaulted constructor
4411 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4412 if (FieldDtor->isDeleted())
4413 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004414 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00004415 AR_accessible)
4416 return true;
4417 }
Alexis Hunt899bd442011-06-10 04:44:37 +00004418
4419 // -- a [non-static data member of class type (or array thereof)] B that
4420 // cannot be [copied] because overload resolution, as applied to B's
4421 // [copy] constructor, results in an ambiguity or a function that is
4422 // deleted or inaccessible from the defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00004423 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4424 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004425 if (!FieldCtor || FieldCtor->isDeleted())
4426 return true;
4427 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4428 PDiag()) != AR_accessible)
4429 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00004430 }
Alexis Hunt913820d2011-05-13 06:10:58 +00004431 }
4432
4433 return false;
4434}
4435
Alexis Huntb2f27802011-05-14 05:23:24 +00004436bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4437 CXXRecordDecl *RD = MD->getParent();
4438 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004439 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004440 return false;
4441
Alexis Hunte77a28f2011-05-18 03:41:58 +00004442 SourceLocation Loc = MD->getLocation();
4443
Alexis Huntb2f27802011-05-14 05:23:24 +00004444 // Do access control from the constructor
4445 ContextRAII MethodContext(*this, MD);
4446
4447 bool Union = RD->isUnion();
4448
Alexis Hunt491ec602011-06-21 23:42:56 +00004449 unsigned ArgQuals =
4450 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4451 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004452
4453 // We do this because we should never actually use an anonymous
4454 // union's constructor.
4455 if (Union && RD->isAnonymousStructOrUnion())
4456 return false;
4457
Alexis Huntb2f27802011-05-14 05:23:24 +00004458 // FIXME: We should put some diagnostic logic right into this function.
4459
Sebastian Redl22653ba2011-08-30 19:58:05 +00004460 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004461 // A defaulted [copy] assignment operator for class X is defined as deleted
4462 // if X has:
4463
4464 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4465 BE = RD->bases_end();
4466 BI != BE; ++BI) {
4467 // We'll handle this one later
4468 if (BI->isVirtual())
4469 continue;
4470
4471 QualType BaseType = BI->getType();
4472 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4473 assert(BaseDecl && "base isn't a CXXRecordDecl");
4474
4475 // -- a [direct base class] B that cannot be [copied] because overload
4476 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004477 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004478 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004479 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4480 0);
4481 if (!CopyOper || CopyOper->isDeleted())
4482 return true;
4483 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004484 return true;
4485 }
4486
4487 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4488 BE = RD->vbases_end();
4489 BI != BE; ++BI) {
4490 QualType BaseType = BI->getType();
4491 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4492 assert(BaseDecl && "base isn't a CXXRecordDecl");
4493
Alexis Huntb2f27802011-05-14 05:23:24 +00004494 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004495 // resolution, as applied to B's [copy] assignment operator, results in
4496 // an ambiguity or a function that is deleted or inaccessible from the
4497 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004498 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4499 0);
4500 if (!CopyOper || CopyOper->isDeleted())
4501 return true;
4502 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004503 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004504 }
4505
4506 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4507 FE = RD->field_end();
4508 FI != FE; ++FI) {
4509 QualType FieldType = Context.getBaseElementType(FI->getType());
4510
4511 // -- a non-static data member of reference type
4512 if (FieldType->isReferenceType())
4513 return true;
4514
4515 // -- a non-static data member of const non-class type (or array thereof)
4516 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4517 return true;
4518
4519 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4520
4521 if (FieldRecord) {
4522 // This is an anonymous union
4523 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4524 // Anonymous unions inside unions do not variant members create
4525 if (!Union) {
4526 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4527 UE = FieldRecord->field_end();
4528 UI != UE; ++UI) {
4529 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4530 CXXRecordDecl *UnionFieldRecord =
4531 UnionFieldType->getAsCXXRecordDecl();
4532
4533 // -- a variant member with a non-trivial [copy] assignment operator
4534 // and X is a union-like class
4535 if (UnionFieldRecord &&
4536 !UnionFieldRecord->hasTrivialCopyAssignment())
4537 return true;
4538 }
4539 }
4540
4541 // Don't try to initalize an anonymous union
4542 continue;
4543 // -- a variant member with a non-trivial [copy] assignment operator
4544 // and X is a union-like class
4545 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4546 return true;
4547 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004548
Alexis Hunt491ec602011-06-21 23:42:56 +00004549 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4550 false, 0);
4551 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004552 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004553 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004554 return true;
4555 }
4556 }
4557
4558 return false;
4559}
4560
4561bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4562 CXXRecordDecl *RD = CD->getParent();
4563 assert(!RD->isDependentType() && "do deletion after instantiation");
4564 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4565 return false;
4566
4567 SourceLocation Loc = CD->getLocation();
4568
4569 // Do access control from the constructor
4570 ContextRAII CtorContext(*this, CD);
4571
4572 bool Union = RD->isUnion();
4573
4574 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4575 "copy assignment arg has no pointee type");
4576
4577 // We do this because we should never actually use an anonymous
4578 // union's constructor.
4579 if (Union && RD->isAnonymousStructOrUnion())
4580 return false;
4581
4582 // C++0x [class.copy]/11
4583 // A defaulted [move] constructor for class X is defined as deleted
4584 // if X has:
4585
4586 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4587 BE = RD->bases_end();
4588 BI != BE; ++BI) {
4589 // We'll handle this one later
4590 if (BI->isVirtual())
4591 continue;
4592
4593 QualType BaseType = BI->getType();
4594 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4595 assert(BaseDecl && "base isn't a CXXRecordDecl");
4596
4597 // -- any [direct base class] of a type with a destructor that is deleted or
4598 // inaccessible from the defaulted constructor
4599 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4600 if (BaseDtor->isDeleted())
4601 return true;
4602 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4603 AR_accessible)
4604 return true;
4605
4606 // -- a [direct base class] B that cannot be [moved] because overload
4607 // resolution, as applied to B's [move] constructor, results in an
4608 // ambiguity or a function that is deleted or inaccessible from the
4609 // defaulted constructor
4610 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4611 if (!BaseCtor || BaseCtor->isDeleted())
4612 return true;
4613 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4614 AR_accessible)
4615 return true;
4616
4617 // -- for a move constructor, a [direct base class] with a type that
4618 // does not have a move constructor and is not trivially copyable.
4619 // If the field isn't a record, it's always trivially copyable.
4620 // A moving constructor could be a copy constructor instead.
4621 if (!BaseCtor->isMoveConstructor() &&
4622 !BaseDecl->isTriviallyCopyable())
4623 return true;
4624 }
4625
4626 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4627 BE = RD->vbases_end();
4628 BI != BE; ++BI) {
4629 QualType BaseType = BI->getType();
4630 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4631 assert(BaseDecl && "base isn't a CXXRecordDecl");
4632
4633 // -- any [virtual base class] of a type with a destructor that is deleted
4634 // or inaccessible from the defaulted constructor
4635 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4636 if (BaseDtor->isDeleted())
4637 return true;
4638 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4639 AR_accessible)
4640 return true;
4641
4642 // -- a [virtual base class] B that cannot be [moved] because overload
4643 // resolution, as applied to B's [move] constructor, results in an
4644 // ambiguity or a function that is deleted or inaccessible from the
4645 // defaulted constructor
4646 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4647 if (!BaseCtor || BaseCtor->isDeleted())
4648 return true;
4649 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4650 AR_accessible)
4651 return true;
4652
4653 // -- for a move constructor, a [virtual base class] with a type that
4654 // does not have a move constructor and is not trivially copyable.
4655 // If the field isn't a record, it's always trivially copyable.
4656 // A moving constructor could be a copy constructor instead.
4657 if (!BaseCtor->isMoveConstructor() &&
4658 !BaseDecl->isTriviallyCopyable())
4659 return true;
4660 }
4661
4662 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4663 FE = RD->field_end();
4664 FI != FE; ++FI) {
4665 QualType FieldType = Context.getBaseElementType(FI->getType());
4666
4667 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4668 // This is an anonymous union
4669 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4670 // Anonymous unions inside unions do not variant members create
4671 if (!Union) {
4672 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4673 UE = FieldRecord->field_end();
4674 UI != UE; ++UI) {
4675 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4676 CXXRecordDecl *UnionFieldRecord =
4677 UnionFieldType->getAsCXXRecordDecl();
4678
4679 // -- a variant member with a non-trivial [move] constructor and X
4680 // is a union-like class
4681 if (UnionFieldRecord &&
4682 !UnionFieldRecord->hasTrivialMoveConstructor())
4683 return true;
4684 }
4685 }
4686
4687 // Don't try to initalize an anonymous union
4688 continue;
4689 } else {
4690 // -- a variant member with a non-trivial [move] constructor and X is a
4691 // union-like class
4692 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4693 return true;
4694
4695 // -- any [non-static data member] of a type with a destructor that is
4696 // deleted or inaccessible from the defaulted constructor
4697 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4698 if (FieldDtor->isDeleted())
4699 return true;
4700 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4701 AR_accessible)
4702 return true;
4703 }
4704
4705 // -- a [non-static data member of class type (or array thereof)] B that
4706 // cannot be [moved] because overload resolution, as applied to B's
4707 // [move] constructor, results in an ambiguity or a function that is
4708 // deleted or inaccessible from the defaulted constructor
4709 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4710 if (!FieldCtor || FieldCtor->isDeleted())
4711 return true;
4712 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4713 PDiag()) != AR_accessible)
4714 return true;
4715
4716 // -- for a move constructor, a [non-static data member] with a type that
4717 // does not have a move constructor and is not trivially copyable.
4718 // If the field isn't a record, it's always trivially copyable.
4719 // A moving constructor could be a copy constructor instead.
4720 if (!FieldCtor->isMoveConstructor() &&
4721 !FieldRecord->isTriviallyCopyable())
4722 return true;
4723 }
4724 }
4725
4726 return false;
4727}
4728
4729bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4730 CXXRecordDecl *RD = MD->getParent();
4731 assert(!RD->isDependentType() && "do deletion after instantiation");
4732 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4733 return false;
4734
4735 SourceLocation Loc = MD->getLocation();
4736
4737 // Do access control from the constructor
4738 ContextRAII MethodContext(*this, MD);
4739
4740 bool Union = RD->isUnion();
4741
4742 // We do this because we should never actually use an anonymous
4743 // union's constructor.
4744 if (Union && RD->isAnonymousStructOrUnion())
4745 return false;
4746
4747 // C++0x [class.copy]/20
4748 // A defaulted [move] assignment operator for class X is defined as deleted
4749 // if X has:
4750
4751 // -- for the move constructor, [...] any direct or indirect virtual base
4752 // class.
4753 if (RD->getNumVBases() != 0)
4754 return true;
4755
4756 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4757 BE = RD->bases_end();
4758 BI != BE; ++BI) {
4759
4760 QualType BaseType = BI->getType();
4761 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4762 assert(BaseDecl && "base isn't a CXXRecordDecl");
4763
4764 // -- a [direct base class] B that cannot be [moved] because overload
4765 // resolution, as applied to B's [move] assignment operator, results in
4766 // an ambiguity or a function that is deleted or inaccessible from the
4767 // assignment operator
4768 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4769 if (!MoveOper || MoveOper->isDeleted())
4770 return true;
4771 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4772 return true;
4773
4774 // -- for the move assignment operator, a [direct base class] with a type
4775 // that does not have a move assignment operator and is not trivially
4776 // copyable.
4777 if (!MoveOper->isMoveAssignmentOperator() &&
4778 !BaseDecl->isTriviallyCopyable())
4779 return true;
4780 }
4781
4782 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4783 FE = RD->field_end();
4784 FI != FE; ++FI) {
4785 QualType FieldType = Context.getBaseElementType(FI->getType());
4786
4787 // -- a non-static data member of reference type
4788 if (FieldType->isReferenceType())
4789 return true;
4790
4791 // -- a non-static data member of const non-class type (or array thereof)
4792 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4793 return true;
4794
4795 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4796
4797 if (FieldRecord) {
4798 // This is an anonymous union
4799 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4800 // Anonymous unions inside unions do not variant members create
4801 if (!Union) {
4802 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4803 UE = FieldRecord->field_end();
4804 UI != UE; ++UI) {
4805 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4806 CXXRecordDecl *UnionFieldRecord =
4807 UnionFieldType->getAsCXXRecordDecl();
4808
4809 // -- a variant member with a non-trivial [move] assignment operator
4810 // and X is a union-like class
4811 if (UnionFieldRecord &&
4812 !UnionFieldRecord->hasTrivialMoveAssignment())
4813 return true;
4814 }
4815 }
4816
4817 // Don't try to initalize an anonymous union
4818 continue;
4819 // -- a variant member with a non-trivial [move] assignment operator
4820 // and X is a union-like class
4821 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4822 return true;
4823 }
4824
4825 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4826 if (!MoveOper || MoveOper->isDeleted())
4827 return true;
4828 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4829 return true;
4830
4831 // -- for the move assignment operator, a [non-static data member] with a
4832 // type that does not have a move assignment operator and is not
4833 // trivially copyable.
4834 if (!MoveOper->isMoveAssignmentOperator() &&
4835 !FieldRecord->isTriviallyCopyable())
4836 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004837 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004838 }
4839
4840 return false;
4841}
4842
Alexis Huntf91729462011-05-12 22:46:25 +00004843bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4844 CXXRecordDecl *RD = DD->getParent();
4845 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004846 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004847 return false;
4848
Alexis Hunte77a28f2011-05-18 03:41:58 +00004849 SourceLocation Loc = DD->getLocation();
4850
Alexis Huntf91729462011-05-12 22:46:25 +00004851 // Do access control from the destructor
4852 ContextRAII CtorContext(*this, DD);
4853
4854 bool Union = RD->isUnion();
4855
Alexis Hunt913820d2011-05-13 06:10:58 +00004856 // We do this because we should never actually use an anonymous
4857 // union's destructor.
4858 if (Union && RD->isAnonymousStructOrUnion())
4859 return false;
4860
Alexis Huntf91729462011-05-12 22:46:25 +00004861 // C++0x [class.dtor]p5
4862 // A defaulted destructor for a class X is defined as deleted if:
4863 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4864 BE = RD->bases_end();
4865 BI != BE; ++BI) {
4866 // We'll handle this one later
4867 if (BI->isVirtual())
4868 continue;
4869
4870 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4871 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4872 assert(BaseDtor && "base has no destructor");
4873
4874 // -- any direct or virtual base class has a deleted destructor or
4875 // a destructor that is inaccessible from the defaulted destructor
4876 if (BaseDtor->isDeleted())
4877 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004878 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004879 AR_accessible)
4880 return true;
4881 }
4882
4883 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4884 BE = RD->vbases_end();
4885 BI != BE; ++BI) {
4886 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4887 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4888 assert(BaseDtor && "base has no destructor");
4889
4890 // -- any direct or virtual base class has a deleted destructor or
4891 // a destructor that is inaccessible from the defaulted destructor
4892 if (BaseDtor->isDeleted())
4893 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004894 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004895 AR_accessible)
4896 return true;
4897 }
4898
4899 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4900 FE = RD->field_end();
4901 FI != FE; ++FI) {
4902 QualType FieldType = Context.getBaseElementType(FI->getType());
4903 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4904 if (FieldRecord) {
4905 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4906 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4907 UE = FieldRecord->field_end();
4908 UI != UE; ++UI) {
4909 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4910 CXXRecordDecl *UnionFieldRecord =
4911 UnionFieldType->getAsCXXRecordDecl();
4912
4913 // -- X is a union-like class that has a variant member with a non-
4914 // trivial destructor.
4915 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4916 return true;
4917 }
4918 // Technically we are supposed to do this next check unconditionally.
4919 // But that makes absolutely no sense.
4920 } else {
4921 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4922
4923 // -- any of the non-static data members has class type M (or array
4924 // thereof) and M has a deleted destructor or a destructor that is
4925 // inaccessible from the defaulted destructor
4926 if (FieldDtor->isDeleted())
4927 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004928 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004929 AR_accessible)
4930 return true;
4931
4932 // -- X is a union-like class that has a variant member with a non-
4933 // trivial destructor.
4934 if (Union && !FieldDtor->isTrivial())
4935 return true;
4936 }
4937 }
4938 }
4939
4940 if (DD->isVirtual()) {
4941 FunctionDecl *OperatorDelete = 0;
4942 DeclarationName Name =
4943 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004944 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004945 false))
4946 return true;
4947 }
4948
4949
4950 return false;
4951}
4952
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004953/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004954namespace {
4955 struct FindHiddenVirtualMethodData {
4956 Sema *S;
4957 CXXMethodDecl *Method;
4958 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004959 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004960 };
4961}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004962
4963/// \brief Member lookup function that determines whether a given C++
4964/// method overloads virtual methods in a base class without overriding any,
4965/// to be used with CXXRecordDecl::lookupInBases().
4966static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4967 CXXBasePath &Path,
4968 void *UserData) {
4969 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4970
4971 FindHiddenVirtualMethodData &Data
4972 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4973
4974 DeclarationName Name = Data.Method->getDeclName();
4975 assert(Name.getNameKind() == DeclarationName::Identifier);
4976
4977 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004978 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004979 for (Path.Decls = BaseRecord->lookup(Name);
4980 Path.Decls.first != Path.Decls.second;
4981 ++Path.Decls.first) {
4982 NamedDecl *D = *Path.Decls.first;
4983 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004984 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004985 foundSameNameMethod = true;
4986 // Interested only in hidden virtual methods.
4987 if (!MD->isVirtual())
4988 continue;
4989 // If the method we are checking overrides a method from its base
4990 // don't warn about the other overloaded methods.
4991 if (!Data.S->IsOverload(Data.Method, MD, false))
4992 return true;
4993 // Collect the overload only if its hidden.
4994 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4995 overloadedMethods.push_back(MD);
4996 }
4997 }
4998
4999 if (foundSameNameMethod)
5000 Data.OverloadedMethods.append(overloadedMethods.begin(),
5001 overloadedMethods.end());
5002 return foundSameNameMethod;
5003}
5004
5005/// \brief See if a method overloads virtual methods in a base class without
5006/// overriding any.
5007void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5008 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00005009 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005010 return;
5011 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5012 return;
5013
5014 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5015 /*bool RecordPaths=*/false,
5016 /*bool DetectVirtual=*/false);
5017 FindHiddenVirtualMethodData Data;
5018 Data.Method = MD;
5019 Data.S = this;
5020
5021 // Keep the base methods that were overriden or introduced in the subclass
5022 // by 'using' in a set. A base method not in this set is hidden.
5023 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5024 res.first != res.second; ++res.first) {
5025 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5026 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5027 E = MD->end_overridden_methods();
5028 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005029 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005030 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5031 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005032 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005033 }
5034
5035 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5036 !Data.OverloadedMethods.empty()) {
5037 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5038 << MD << (Data.OverloadedMethods.size() > 1);
5039
5040 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5041 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5042 Diag(overloadedMD->getLocation(),
5043 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5044 }
5045 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005046}
5047
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005048void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005049 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005050 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005051 SourceLocation RBrac,
5052 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005053 if (!TagDecl)
5054 return;
Mike Stump11289f42009-09-09 15:08:12 +00005055
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005056 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005057
David Blaikie751c5582011-09-22 02:58:26 +00005058 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005059 // strict aliasing violation!
5060 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005061 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005062
Douglas Gregor0be31a22010-07-02 17:43:08 +00005063 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005064 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005065}
5066
Douglas Gregor05379422008-11-03 17:51:48 +00005067/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5068/// special functions, such as the default constructor, copy
5069/// constructor, or destructor, to the given C++ class (C++
5070/// [special]p1). This routine can only be executed just before the
5071/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005072void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005073 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005074 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005075
Douglas Gregor54be3392010-07-01 17:57:27 +00005076 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00005077 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005078
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005079 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5080 ++ASTContext::NumImplicitCopyAssignmentOperators;
5081
5082 // If we have a dynamic class, then the copy assignment operator may be
5083 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5084 // it shows up in the right place in the vtable and that we diagnose
5085 // problems with the implicit exception specification.
5086 if (ClassDecl->isDynamicClass())
5087 DeclareImplicitCopyAssignment(ClassDecl);
5088 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005089
Douglas Gregor7454c562010-07-02 20:37:36 +00005090 if (!ClassDecl->hasUserDeclaredDestructor()) {
5091 ++ASTContext::NumImplicitDestructors;
5092
5093 // If we have a dynamic class, then the destructor may be virtual, so we
5094 // have to declare the destructor immediately. This ensures that, e.g., it
5095 // shows up in the right place in the vtable and that we diagnose problems
5096 // with the implicit exception specification.
5097 if (ClassDecl->isDynamicClass())
5098 DeclareImplicitDestructor(ClassDecl);
5099 }
Douglas Gregor05379422008-11-03 17:51:48 +00005100}
5101
Francois Pichet1c229c02011-04-22 22:18:13 +00005102void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5103 if (!D)
5104 return;
5105
5106 int NumParamList = D->getNumTemplateParameterLists();
5107 for (int i = 0; i < NumParamList; i++) {
5108 TemplateParameterList* Params = D->getTemplateParameterList(i);
5109 for (TemplateParameterList::iterator Param = Params->begin(),
5110 ParamEnd = Params->end();
5111 Param != ParamEnd; ++Param) {
5112 NamedDecl *Named = cast<NamedDecl>(*Param);
5113 if (Named->getDeclName()) {
5114 S->AddDecl(Named);
5115 IdResolver.AddDecl(Named);
5116 }
5117 }
5118 }
5119}
5120
John McCall48871652010-08-21 09:40:31 +00005121void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005122 if (!D)
5123 return;
5124
5125 TemplateParameterList *Params = 0;
5126 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5127 Params = Template->getTemplateParameters();
5128 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5129 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5130 Params = PartialSpec->getTemplateParameters();
5131 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005132 return;
5133
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005134 for (TemplateParameterList::iterator Param = Params->begin(),
5135 ParamEnd = Params->end();
5136 Param != ParamEnd; ++Param) {
5137 NamedDecl *Named = cast<NamedDecl>(*Param);
5138 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005139 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005140 IdResolver.AddDecl(Named);
5141 }
5142 }
5143}
5144
John McCall48871652010-08-21 09:40:31 +00005145void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005146 if (!RecordD) return;
5147 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005148 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005149 PushDeclContext(S, Record);
5150}
5151
John McCall48871652010-08-21 09:40:31 +00005152void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005153 if (!RecordD) return;
5154 PopDeclContext();
5155}
5156
Douglas Gregor4d87df52008-12-16 21:30:33 +00005157/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5158/// parsing a top-level (non-nested) C++ class, and we are now
5159/// parsing those parts of the given Method declaration that could
5160/// not be parsed earlier (C++ [class.mem]p2), such as default
5161/// arguments. This action should enter the scope of the given
5162/// Method declaration as if we had just parsed the qualified method
5163/// name. However, it should not bring the parameters into scope;
5164/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005165void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005166}
5167
5168/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5169/// C++ method declaration. We're (re-)introducing the given
5170/// function parameter into scope for use in parsing later parts of
5171/// the method declaration. For example, we could see an
5172/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00005173void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005174 if (!ParamD)
5175 return;
Mike Stump11289f42009-09-09 15:08:12 +00005176
John McCall48871652010-08-21 09:40:31 +00005177 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00005178
5179 // If this parameter has an unparsed default argument, clear it out
5180 // to make way for the parsed default argument.
5181 if (Param->hasUnparsedDefaultArg())
5182 Param->setDefaultArg(0);
5183
John McCall48871652010-08-21 09:40:31 +00005184 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005185 if (Param->getDeclName())
5186 IdResolver.AddDecl(Param);
5187}
5188
5189/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5190/// processing the delayed method declaration for Method. The method
5191/// declaration is now considered finished. There may be a separate
5192/// ActOnStartOfFunctionDef action later (not necessarily
5193/// immediately!) for this method, if it was also defined inside the
5194/// class body.
John McCall48871652010-08-21 09:40:31 +00005195void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005196 if (!MethodD)
5197 return;
Mike Stump11289f42009-09-09 15:08:12 +00005198
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005199 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005200
John McCall48871652010-08-21 09:40:31 +00005201 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005202
5203 // Now that we have our default arguments, check the constructor
5204 // again. It could produce additional diagnostics or affect whether
5205 // the class has implicitly-declared destructors, among other
5206 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005207 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5208 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005209
5210 // Check the default arguments, which we may have added.
5211 if (!Method->isInvalidDecl())
5212 CheckCXXDefaultArguments(Method);
5213}
5214
Douglas Gregor831c93f2008-11-05 20:51:48 +00005215/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005216/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005217/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005218/// emit diagnostics and set the invalid bit to true. In any case, the type
5219/// will be updated to reflect a well-formed type for the constructor and
5220/// returned.
5221QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005222 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005223 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005224
5225 // C++ [class.ctor]p3:
5226 // A constructor shall not be virtual (10.3) or static (9.4). A
5227 // constructor can be invoked for a const, volatile or const
5228 // volatile object. A constructor shall not be declared const,
5229 // volatile, or const volatile (9.3.2).
5230 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005231 if (!D.isInvalidType())
5232 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5233 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5234 << SourceRange(D.getIdentifierLoc());
5235 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005236 }
John McCall8e7d6562010-08-26 03:08:43 +00005237 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005238 if (!D.isInvalidType())
5239 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5240 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5241 << SourceRange(D.getIdentifierLoc());
5242 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005243 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005244 }
Mike Stump11289f42009-09-09 15:08:12 +00005245
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005246 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005247 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005248 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005249 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5250 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005251 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005252 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5253 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005254 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005255 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5256 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005257 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005258 }
Mike Stump11289f42009-09-09 15:08:12 +00005259
Douglas Gregordb9d6642011-01-26 05:01:58 +00005260 // C++0x [class.ctor]p4:
5261 // A constructor shall not be declared with a ref-qualifier.
5262 if (FTI.hasRefQualifier()) {
5263 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5264 << FTI.RefQualifierIsLValueRef
5265 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5266 D.setInvalidType();
5267 }
5268
Douglas Gregor831c93f2008-11-05 20:51:48 +00005269 // Rebuild the function type "R" without any type qualifiers (in
5270 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005271 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005272 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005273 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5274 return R;
5275
5276 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5277 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005278 EPI.RefQualifier = RQ_None;
5279
Chris Lattner38378bf2009-04-25 08:28:21 +00005280 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005281 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005282}
5283
Douglas Gregor4d87df52008-12-16 21:30:33 +00005284/// CheckConstructor - Checks a fully-formed constructor for
5285/// well-formedness, issuing any diagnostics required. Returns true if
5286/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005287void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005288 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005289 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5290 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005291 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005292
5293 // C++ [class.copy]p3:
5294 // A declaration of a constructor for a class X is ill-formed if
5295 // its first parameter is of type (optionally cv-qualified) X and
5296 // either there are no other parameters or else all other
5297 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005298 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005299 ((Constructor->getNumParams() == 1) ||
5300 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005301 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5302 Constructor->getTemplateSpecializationKind()
5303 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005304 QualType ParamType = Constructor->getParamDecl(0)->getType();
5305 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5306 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005307 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005308 const char *ConstRef
5309 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5310 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005311 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005312 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005313
5314 // FIXME: Rather that making the constructor invalid, we should endeavor
5315 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005316 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005317 }
5318 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005319}
5320
John McCalldeb646e2010-08-04 01:04:25 +00005321/// CheckDestructor - Checks a fully-formed destructor definition for
5322/// well-formedness, issuing any diagnostics required. Returns true
5323/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005324bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005325 CXXRecordDecl *RD = Destructor->getParent();
5326
5327 if (Destructor->isVirtual()) {
5328 SourceLocation Loc;
5329
5330 if (!Destructor->isImplicit())
5331 Loc = Destructor->getLocation();
5332 else
5333 Loc = RD->getLocation();
5334
5335 // If we have a virtual destructor, look up the deallocation function
5336 FunctionDecl *OperatorDelete = 0;
5337 DeclarationName Name =
5338 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005339 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005340 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005341
5342 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005343
5344 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005345 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005346
5347 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005348}
5349
Mike Stump11289f42009-09-09 15:08:12 +00005350static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005351FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5352 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5353 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005354 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005355}
5356
Douglas Gregor831c93f2008-11-05 20:51:48 +00005357/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5358/// the well-formednes of the destructor declarator @p D with type @p
5359/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005360/// emit diagnostics and set the declarator to invalid. Even if this happens,
5361/// will be updated to reflect a well-formed type for the destructor and
5362/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005363QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005364 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005365 // C++ [class.dtor]p1:
5366 // [...] A typedef-name that names a class is a class-name
5367 // (7.1.3); however, a typedef-name that names a class shall not
5368 // be used as the identifier in the declarator for a destructor
5369 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005370 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005371 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005372 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005373 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005374 else if (const TemplateSpecializationType *TST =
5375 DeclaratorType->getAs<TemplateSpecializationType>())
5376 if (TST->isTypeAlias())
5377 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5378 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005379
5380 // C++ [class.dtor]p2:
5381 // A destructor is used to destroy objects of its class type. A
5382 // destructor takes no parameters, and no return type can be
5383 // specified for it (not even void). The address of a destructor
5384 // shall not be taken. A destructor shall not be static. A
5385 // destructor can be invoked for a const, volatile or const
5386 // volatile object. A destructor shall not be declared const,
5387 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005388 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005389 if (!D.isInvalidType())
5390 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5391 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005392 << SourceRange(D.getIdentifierLoc())
5393 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5394
John McCall8e7d6562010-08-26 03:08:43 +00005395 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005396 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005397 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005398 // Destructors don't have return types, but the parser will
5399 // happily parse something like:
5400 //
5401 // class X {
5402 // float ~X();
5403 // };
5404 //
5405 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005406 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5407 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5408 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005409 }
Mike Stump11289f42009-09-09 15:08:12 +00005410
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005411 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005412 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005413 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005414 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5415 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005416 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005417 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5418 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005419 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005420 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5421 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005422 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005423 }
5424
Douglas Gregordb9d6642011-01-26 05:01:58 +00005425 // C++0x [class.dtor]p2:
5426 // A destructor shall not be declared with a ref-qualifier.
5427 if (FTI.hasRefQualifier()) {
5428 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5429 << FTI.RefQualifierIsLValueRef
5430 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5431 D.setInvalidType();
5432 }
5433
Douglas Gregor831c93f2008-11-05 20:51:48 +00005434 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005435 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005436 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5437
5438 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005439 FTI.freeArgs();
5440 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005441 }
5442
Mike Stump11289f42009-09-09 15:08:12 +00005443 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005444 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005445 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005446 D.setInvalidType();
5447 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005448
5449 // Rebuild the function type "R" without any type qualifiers or
5450 // parameters (in case any of the errors above fired) and with
5451 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005452 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005453 if (!D.isInvalidType())
5454 return R;
5455
Douglas Gregor95755162010-07-01 05:10:53 +00005456 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005457 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5458 EPI.Variadic = false;
5459 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005460 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005461 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005462}
5463
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005464/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5465/// well-formednes of the conversion function declarator @p D with
5466/// type @p R. If there are any errors in the declarator, this routine
5467/// will emit diagnostics and return true. Otherwise, it will return
5468/// false. Either way, the type @p R will be updated to reflect a
5469/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005470void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005471 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005472 // C++ [class.conv.fct]p1:
5473 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005474 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005475 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005476 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005477 if (!D.isInvalidType())
5478 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5479 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5480 << SourceRange(D.getIdentifierLoc());
5481 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005482 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005483 }
John McCall212fa2e2010-04-13 00:04:31 +00005484
5485 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5486
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005487 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005488 // Conversion functions don't have return types, but the parser will
5489 // happily parse something like:
5490 //
5491 // class X {
5492 // float operator bool();
5493 // };
5494 //
5495 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005496 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5497 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5498 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005499 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005500 }
5501
John McCall212fa2e2010-04-13 00:04:31 +00005502 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5503
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005504 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005505 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005506 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5507
5508 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005509 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005510 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005511 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005512 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005513 D.setInvalidType();
5514 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005515
John McCall212fa2e2010-04-13 00:04:31 +00005516 // Diagnose "&operator bool()" and other such nonsense. This
5517 // is actually a gcc extension which we don't support.
5518 if (Proto->getResultType() != ConvType) {
5519 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5520 << Proto->getResultType();
5521 D.setInvalidType();
5522 ConvType = Proto->getResultType();
5523 }
5524
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005525 // C++ [class.conv.fct]p4:
5526 // The conversion-type-id shall not represent a function type nor
5527 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005528 if (ConvType->isArrayType()) {
5529 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5530 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005531 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005532 } else if (ConvType->isFunctionType()) {
5533 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5534 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005535 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005536 }
5537
5538 // Rebuild the function type "R" without any parameters (in case any
5539 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005540 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005541 if (D.isInvalidType())
5542 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005543
Douglas Gregor5fb53972009-01-14 15:45:31 +00005544 // C++0x explicit conversion operators.
5545 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00005546 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00005547 diag::warn_explicit_conversion_functions)
5548 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005549}
5550
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005551/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5552/// the declaration of the given C++ conversion function. This routine
5553/// is responsible for recording the conversion function in the C++
5554/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005555Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005556 assert(Conversion && "Expected to receive a conversion function declaration");
5557
Douglas Gregor4287b372008-12-12 08:25:50 +00005558 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005559
5560 // Make sure we aren't redeclaring the conversion function.
5561 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005562
5563 // C++ [class.conv.fct]p1:
5564 // [...] A conversion function is never used to convert a
5565 // (possibly cv-qualified) object to the (possibly cv-qualified)
5566 // same object type (or a reference to it), to a (possibly
5567 // cv-qualified) base class of that type (or a reference to it),
5568 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005569 // FIXME: Suppress this warning if the conversion function ends up being a
5570 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005571 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005572 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005573 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005574 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005575 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5576 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005577 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005578 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005579 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5580 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005581 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005582 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005583 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005584 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005585 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005586 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005587 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005588 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005589 }
5590
Douglas Gregor457104e2010-09-29 04:25:11 +00005591 if (FunctionTemplateDecl *ConversionTemplate
5592 = Conversion->getDescribedFunctionTemplate())
5593 return ConversionTemplate;
5594
John McCall48871652010-08-21 09:40:31 +00005595 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005596}
5597
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005598//===----------------------------------------------------------------------===//
5599// Namespace Handling
5600//===----------------------------------------------------------------------===//
5601
John McCallb1be5232010-08-26 09:15:37 +00005602
5603
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005604/// ActOnStartNamespaceDef - This is called at the start of a namespace
5605/// definition.
John McCall48871652010-08-21 09:40:31 +00005606Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005607 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005608 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005609 SourceLocation IdentLoc,
5610 IdentifierInfo *II,
5611 SourceLocation LBrace,
5612 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005613 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5614 // For anonymous namespace, take the location of the left brace.
5615 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00005616 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005617 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005618 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005619
5620 Scope *DeclRegionScope = NamespcScope->getParent();
5621
Anders Carlssona7bcade2010-02-07 01:09:23 +00005622 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5623
John McCall2faf32c2010-12-10 02:59:44 +00005624 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5625 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00005626
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005627 if (II) {
5628 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005629 // The identifier in an original-namespace-definition shall not
5630 // have been previously defined in the declarative region in
5631 // which the original-namespace-definition appears. The
5632 // identifier in an original-namespace-definition is the name of
5633 // the namespace. Subsequently in that declarative region, it is
5634 // treated as an original-namespace-name.
5635 //
5636 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005637 // look through using directives, just look for any ordinary names.
5638
5639 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5640 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5641 Decl::IDNS_Namespace;
5642 NamedDecl *PrevDecl = 0;
5643 for (DeclContext::lookup_result R
5644 = CurContext->getRedeclContext()->lookup(II);
5645 R.first != R.second; ++R.first) {
5646 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5647 PrevDecl = *R.first;
5648 break;
5649 }
5650 }
5651
Douglas Gregor91f84212008-12-11 16:49:14 +00005652 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5653 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005654 if (Namespc->isInline() != OrigNS->isInline()) {
5655 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00005656 if (OrigNS->isInline()) {
5657 // The user probably just forgot the 'inline', so suggest that it
5658 // be added back.
5659 Diag(Namespc->getLocation(),
5660 diag::warn_inline_namespace_reopened_noninline)
5661 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5662 } else {
5663 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5664 << Namespc->isInline();
5665 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005666 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00005667
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005668 // Recover by ignoring the new namespace's inline status.
5669 Namespc->setInline(OrigNS->isInline());
5670 }
5671
Douglas Gregor91f84212008-12-11 16:49:14 +00005672 // Attach this namespace decl to the chain of extended namespace
5673 // definitions.
5674 OrigNS->setNextNamespace(Namespc);
5675 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005676
Mike Stump11289f42009-09-09 15:08:12 +00005677 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00005678 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00005679 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00005680 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005681 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005682 } else if (PrevDecl) {
5683 // This is an invalid name redefinition.
5684 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5685 << Namespc->getDeclName();
5686 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5687 Namespc->setInvalidDecl();
5688 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00005689 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005690 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005691 // This is the first "real" definition of the namespace "std", so update
5692 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005693 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005694 // We had already defined a dummy namespace "std". Link this new
5695 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005696 StdNS->setNextNamespace(Namespc);
5697 StdNS->setLocation(IdentLoc);
5698 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00005699 }
5700
5701 // Make our StdNamespace cache point at the first real definition of the
5702 // "std" namespace.
5703 StdNamespace = Namespc;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005704
5705 // Add this instance of "std" to the set of known namespaces
5706 KnownNamespaces[Namespc] = false;
5707 } else if (!Namespc->isInline()) {
5708 // Since this is an "original" namespace, add it to the known set of
5709 // namespaces if it is not an inline namespace.
5710 KnownNamespaces[Namespc] = false;
Mike Stump11289f42009-09-09 15:08:12 +00005711 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005712
5713 PushOnScopeChains(Namespc, DeclRegionScope);
5714 } else {
John McCall4fa53422009-10-01 00:25:31 +00005715 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00005716 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00005717
5718 // Link the anonymous namespace into its parent.
5719 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00005720 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005721 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5722 PrevDecl = TU->getAnonymousNamespace();
5723 TU->setAnonymousNamespace(Namespc);
5724 } else {
5725 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5726 PrevDecl = ND->getAnonymousNamespace();
5727 ND->setAnonymousNamespace(Namespc);
5728 }
5729
5730 // Link the anonymous namespace with its previous declaration.
5731 if (PrevDecl) {
5732 assert(PrevDecl->isAnonymousNamespace());
5733 assert(!PrevDecl->getNextNamespace());
5734 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5735 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005736
5737 if (Namespc->isInline() != PrevDecl->isInline()) {
5738 // inline-ness must match
5739 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5740 << Namespc->isInline();
5741 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5742 Namespc->setInvalidDecl();
5743 // Recover by ignoring the new namespace's inline status.
5744 Namespc->setInline(PrevDecl->isInline());
5745 }
John McCall0db42252009-12-16 02:06:49 +00005746 }
John McCall4fa53422009-10-01 00:25:31 +00005747
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005748 CurContext->addDecl(Namespc);
5749
John McCall4fa53422009-10-01 00:25:31 +00005750 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5751 // behaves as if it were replaced by
5752 // namespace unique { /* empty body */ }
5753 // using namespace unique;
5754 // namespace unique { namespace-body }
5755 // where all occurrences of 'unique' in a translation unit are
5756 // replaced by the same identifier and this identifier differs
5757 // from all other identifiers in the entire program.
5758
5759 // We just create the namespace with an empty name and then add an
5760 // implicit using declaration, just like the standard suggests.
5761 //
5762 // CodeGen enforces the "universally unique" aspect by giving all
5763 // declarations semantically contained within an anonymous
5764 // namespace internal linkage.
5765
John McCall0db42252009-12-16 02:06:49 +00005766 if (!PrevDecl) {
5767 UsingDirectiveDecl* UD
5768 = UsingDirectiveDecl::Create(Context, CurContext,
5769 /* 'using' */ LBrace,
5770 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005771 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005772 /* identifier */ SourceLocation(),
5773 Namespc,
5774 /* Ancestor */ CurContext);
5775 UD->setImplicit();
5776 CurContext->addDecl(UD);
5777 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005778 }
5779
5780 // Although we could have an invalid decl (i.e. the namespace name is a
5781 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005782 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5783 // for the namespace has the declarations that showed up in that particular
5784 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005785 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005786 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005787}
5788
Sebastian Redla6602e92009-11-23 15:34:23 +00005789/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5790/// is a namespace alias, returns the namespace it points to.
5791static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5792 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5793 return AD->getNamespace();
5794 return dyn_cast_or_null<NamespaceDecl>(D);
5795}
5796
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005797/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5798/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005799void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005800 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5801 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005802 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005803 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005804 if (Namespc->hasAttr<VisibilityAttr>())
5805 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005806}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005807
John McCall28a0cf72010-08-25 07:42:41 +00005808CXXRecordDecl *Sema::getStdBadAlloc() const {
5809 return cast_or_null<CXXRecordDecl>(
5810 StdBadAlloc.get(Context.getExternalSource()));
5811}
5812
5813NamespaceDecl *Sema::getStdNamespace() const {
5814 return cast_or_null<NamespaceDecl>(
5815 StdNamespace.get(Context.getExternalSource()));
5816}
5817
Douglas Gregorcdf87022010-06-29 17:53:46 +00005818/// \brief Retrieve the special "std" namespace, which may require us to
5819/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005820NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005821 if (!StdNamespace) {
5822 // The "std" namespace has not yet been defined, so build one implicitly.
5823 StdNamespace = NamespaceDecl::Create(Context,
5824 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005825 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00005826 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005827 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005828 }
5829
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005830 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005831}
5832
Douglas Gregora172e082011-03-26 22:25:30 +00005833/// \brief Determine whether a using statement is in a context where it will be
5834/// apply in all contexts.
5835static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5836 switch (CurContext->getDeclKind()) {
5837 case Decl::TranslationUnit:
5838 return true;
5839 case Decl::LinkageSpec:
5840 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5841 default:
5842 return false;
5843 }
5844}
5845
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005846static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5847 CXXScopeSpec &SS,
5848 SourceLocation IdentLoc,
5849 IdentifierInfo *Ident) {
5850 R.clear();
5851 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5852 R.getLookupKind(), Sc, &SS, NULL,
5853 false, S.CTC_NoKeywords, NULL)) {
5854 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5855 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5856 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5857 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5858 if (DeclContext *DC = S.computeDeclContext(SS, false))
5859 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5860 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5861 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5862 else
5863 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5864 << Ident << CorrectedQuotedStr
5865 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5866
5867 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5868 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5869
5870 Ident = Corrected.getCorrectionAsIdentifierInfo();
5871 R.addDecl(Corrected.getCorrectionDecl());
5872 return true;
5873 }
5874 R.setLookupName(Ident);
5875 }
5876 return false;
5877}
5878
John McCall48871652010-08-21 09:40:31 +00005879Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005880 SourceLocation UsingLoc,
5881 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005882 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005883 SourceLocation IdentLoc,
5884 IdentifierInfo *NamespcName,
5885 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00005886 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5887 assert(NamespcName && "Invalid NamespcName.");
5888 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00005889
5890 // This can only happen along a recovery path.
5891 while (S->getFlags() & Scope::TemplateParamScope)
5892 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00005893 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00005894
Douglas Gregor889ceb72009-02-03 19:21:40 +00005895 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00005896 NestedNameSpecifier *Qualifier = 0;
5897 if (SS.isSet())
5898 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5899
Douglas Gregor34074322009-01-14 22:20:51 +00005900 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005901 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5902 LookupParsedName(R, S, &SS);
5903 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005904 return 0;
John McCall27b18f82009-11-17 02:14:36 +00005905
Douglas Gregorcdf87022010-06-29 17:53:46 +00005906 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005907 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005908 // Allow "using namespace std;" or "using namespace ::std;" even if
5909 // "std" hasn't been defined yet, for GCC compatibility.
5910 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5911 NamespcName->isStr("std")) {
5912 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005913 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00005914 R.resolveKind();
5915 }
5916 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005917 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005918 }
5919
John McCall9f3059a2009-10-09 21:13:30 +00005920 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00005921 NamedDecl *Named = R.getFoundDecl();
5922 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5923 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00005924 // C++ [namespace.udir]p1:
5925 // A using-directive specifies that the names in the nominated
5926 // namespace can be used in the scope in which the
5927 // using-directive appears after the using-directive. During
5928 // unqualified name lookup (3.4.1), the names appear as if they
5929 // were declared in the nearest enclosing namespace which
5930 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00005931 // namespace. [Note: in this context, "contains" means "contains
5932 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00005933
5934 // Find enclosing context containing both using-directive and
5935 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00005936 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005937 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5938 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5939 CommonAncestor = CommonAncestor->getParent();
5940
Sebastian Redla6602e92009-11-23 15:34:23 +00005941 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00005942 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00005943 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005944
Douglas Gregora172e082011-03-26 22:25:30 +00005945 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00005946 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005947 Diag(IdentLoc, diag::warn_using_directive_in_header);
5948 }
5949
Douglas Gregor889ceb72009-02-03 19:21:40 +00005950 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005951 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00005952 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00005953 }
5954
Douglas Gregor889ceb72009-02-03 19:21:40 +00005955 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00005956 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00005957}
5958
5959void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5960 // If scope has associated entity, then using directive is at namespace
5961 // or translation unit scope. We add UsingDirectiveDecls, into
5962 // it's lookup structure.
5963 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005964 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005965 else
5966 // Otherwise it is block-sope. using-directives will affect lookup
5967 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00005968 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005969}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005970
Douglas Gregorfec52632009-06-20 00:51:54 +00005971
John McCall48871652010-08-21 09:40:31 +00005972Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00005973 AccessSpecifier AS,
5974 bool HasUsingKeyword,
5975 SourceLocation UsingLoc,
5976 CXXScopeSpec &SS,
5977 UnqualifiedId &Name,
5978 AttributeList *AttrList,
5979 bool IsTypeName,
5980 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00005981 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00005982
Douglas Gregor220f4272009-11-04 16:30:06 +00005983 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00005984 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00005985 case UnqualifiedId::IK_Identifier:
5986 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00005987 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00005988 case UnqualifiedId::IK_ConversionFunctionId:
5989 break;
5990
5991 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005992 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00005993 // C++0x inherited constructors.
5994 if (getLangOptions().CPlusPlus0x) break;
5995
Douglas Gregor220f4272009-11-04 16:30:06 +00005996 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5997 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005998 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005999
6000 case UnqualifiedId::IK_DestructorName:
6001 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6002 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006003 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006004
6005 case UnqualifiedId::IK_TemplateId:
6006 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6007 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006008 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006009 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006010
6011 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6012 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006013 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00006014 return 0;
John McCall3969e302009-12-08 07:46:18 +00006015
John McCalla0097262009-12-11 02:10:03 +00006016 // Warn about using declarations.
6017 // TODO: store that the declaration was written without 'using' and
6018 // talk about access decls instead of using decls in the
6019 // diagnostics.
6020 if (!HasUsingKeyword) {
6021 UsingLoc = Name.getSourceRange().getBegin();
6022
6023 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00006024 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00006025 }
6026
Douglas Gregorc4356532010-12-16 00:46:58 +00006027 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6028 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6029 return 0;
6030
John McCall3f746822009-11-17 05:59:44 +00006031 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006032 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006033 /* IsInstantiation */ false,
6034 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00006035 if (UD)
6036 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00006037
John McCall48871652010-08-21 09:40:31 +00006038 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00006039}
6040
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006041/// \brief Determine whether a using declaration considers the given
6042/// declarations as "equivalent", e.g., if they are redeclarations of
6043/// the same entity or are both typedefs of the same type.
6044static bool
6045IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6046 bool &SuppressRedeclaration) {
6047 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6048 SuppressRedeclaration = false;
6049 return true;
6050 }
6051
Richard Smithdda56e42011-04-15 14:24:37 +00006052 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6053 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006054 SuppressRedeclaration = true;
6055 return Context.hasSameType(TD1->getUnderlyingType(),
6056 TD2->getUnderlyingType());
6057 }
6058
6059 return false;
6060}
6061
6062
John McCall84d87672009-12-10 09:41:52 +00006063/// Determines whether to create a using shadow decl for a particular
6064/// decl, given the set of decls existing prior to this using lookup.
6065bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6066 const LookupResult &Previous) {
6067 // Diagnose finding a decl which is not from a base class of the
6068 // current class. We do this now because there are cases where this
6069 // function will silently decide not to build a shadow decl, which
6070 // will pre-empt further diagnostics.
6071 //
6072 // We don't need to do this in C++0x because we do the check once on
6073 // the qualifier.
6074 //
6075 // FIXME: diagnose the following if we care enough:
6076 // struct A { int foo; };
6077 // struct B : A { using A::foo; };
6078 // template <class T> struct C : A {};
6079 // template <class T> struct D : C<T> { using B::foo; } // <---
6080 // This is invalid (during instantiation) in C++03 because B::foo
6081 // resolves to the using decl in B, which is not a base class of D<T>.
6082 // We can't diagnose it immediately because C<T> is an unknown
6083 // specialization. The UsingShadowDecl in D<T> then points directly
6084 // to A::foo, which will look well-formed when we instantiate.
6085 // The right solution is to not collapse the shadow-decl chain.
6086 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6087 DeclContext *OrigDC = Orig->getDeclContext();
6088
6089 // Handle enums and anonymous structs.
6090 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6091 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6092 while (OrigRec->isAnonymousStructOrUnion())
6093 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6094
6095 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6096 if (OrigDC == CurContext) {
6097 Diag(Using->getLocation(),
6098 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006099 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006100 Diag(Orig->getLocation(), diag::note_using_decl_target);
6101 return true;
6102 }
6103
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006104 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00006105 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006106 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00006107 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006108 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006109 Diag(Orig->getLocation(), diag::note_using_decl_target);
6110 return true;
6111 }
6112 }
6113
6114 if (Previous.empty()) return false;
6115
6116 NamedDecl *Target = Orig;
6117 if (isa<UsingShadowDecl>(Target))
6118 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6119
John McCalla17e83e2009-12-11 02:33:26 +00006120 // If the target happens to be one of the previous declarations, we
6121 // don't have a conflict.
6122 //
6123 // FIXME: but we might be increasing its access, in which case we
6124 // should redeclare it.
6125 NamedDecl *NonTag = 0, *Tag = 0;
6126 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6127 I != E; ++I) {
6128 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006129 bool Result;
6130 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6131 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00006132
6133 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6134 }
6135
John McCall84d87672009-12-10 09:41:52 +00006136 if (Target->isFunctionOrFunctionTemplate()) {
6137 FunctionDecl *FD;
6138 if (isa<FunctionTemplateDecl>(Target))
6139 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6140 else
6141 FD = cast<FunctionDecl>(Target);
6142
6143 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00006144 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00006145 case Ovl_Overload:
6146 return false;
6147
6148 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00006149 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006150 break;
6151
6152 // We found a decl with the exact signature.
6153 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006154 // If we're in a record, we want to hide the target, so we
6155 // return true (without a diagnostic) to tell the caller not to
6156 // build a shadow decl.
6157 if (CurContext->isRecord())
6158 return true;
6159
6160 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00006161 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006162 break;
6163 }
6164
6165 Diag(Target->getLocation(), diag::note_using_decl_target);
6166 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6167 return true;
6168 }
6169
6170 // Target is not a function.
6171
John McCall84d87672009-12-10 09:41:52 +00006172 if (isa<TagDecl>(Target)) {
6173 // No conflict between a tag and a non-tag.
6174 if (!Tag) return false;
6175
John McCalle29c5cd2009-12-10 19:51:03 +00006176 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006177 Diag(Target->getLocation(), diag::note_using_decl_target);
6178 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6179 return true;
6180 }
6181
6182 // No conflict between a tag and a non-tag.
6183 if (!NonTag) return false;
6184
John McCalle29c5cd2009-12-10 19:51:03 +00006185 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006186 Diag(Target->getLocation(), diag::note_using_decl_target);
6187 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6188 return true;
6189}
6190
John McCall3f746822009-11-17 05:59:44 +00006191/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00006192UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00006193 UsingDecl *UD,
6194 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00006195
6196 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00006197 NamedDecl *Target = Orig;
6198 if (isa<UsingShadowDecl>(Target)) {
6199 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6200 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006201 }
6202
6203 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006204 = UsingShadowDecl::Create(Context, CurContext,
6205 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006206 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006207
6208 Shadow->setAccess(UD->getAccess());
6209 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6210 Shadow->setInvalidDecl();
6211
John McCall3f746822009-11-17 05:59:44 +00006212 if (S)
John McCall3969e302009-12-08 07:46:18 +00006213 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006214 else
John McCall3969e302009-12-08 07:46:18 +00006215 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006216
John McCall3969e302009-12-08 07:46:18 +00006217
John McCall84d87672009-12-10 09:41:52 +00006218 return Shadow;
6219}
John McCall3969e302009-12-08 07:46:18 +00006220
John McCall84d87672009-12-10 09:41:52 +00006221/// Hides a using shadow declaration. This is required by the current
6222/// using-decl implementation when a resolvable using declaration in a
6223/// class is followed by a declaration which would hide or override
6224/// one or more of the using decl's targets; for example:
6225///
6226/// struct Base { void foo(int); };
6227/// struct Derived : Base {
6228/// using Base::foo;
6229/// void foo(int);
6230/// };
6231///
6232/// The governing language is C++03 [namespace.udecl]p12:
6233///
6234/// When a using-declaration brings names from a base class into a
6235/// derived class scope, member functions in the derived class
6236/// override and/or hide member functions with the same name and
6237/// parameter types in a base class (rather than conflicting).
6238///
6239/// There are two ways to implement this:
6240/// (1) optimistically create shadow decls when they're not hidden
6241/// by existing declarations, or
6242/// (2) don't create any shadow decls (or at least don't make them
6243/// visible) until we've fully parsed/instantiated the class.
6244/// The problem with (1) is that we might have to retroactively remove
6245/// a shadow decl, which requires several O(n) operations because the
6246/// decl structures are (very reasonably) not designed for removal.
6247/// (2) avoids this but is very fiddly and phase-dependent.
6248void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006249 if (Shadow->getDeclName().getNameKind() ==
6250 DeclarationName::CXXConversionFunctionName)
6251 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6252
John McCall84d87672009-12-10 09:41:52 +00006253 // Remove it from the DeclContext...
6254 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006255
John McCall84d87672009-12-10 09:41:52 +00006256 // ...and the scope, if applicable...
6257 if (S) {
John McCall48871652010-08-21 09:40:31 +00006258 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00006259 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006260 }
6261
John McCall84d87672009-12-10 09:41:52 +00006262 // ...and the using decl.
6263 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6264
6265 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00006266 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00006267}
6268
John McCalle61f2ba2009-11-18 02:36:19 +00006269/// Builds a using declaration.
6270///
6271/// \param IsInstantiation - Whether this call arises from an
6272/// instantiation of an unresolved using declaration. We treat
6273/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00006274NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6275 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006276 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006277 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00006278 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006279 bool IsInstantiation,
6280 bool IsTypeName,
6281 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00006282 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006283 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00006284 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00006285
Anders Carlssonf038fc22009-08-28 05:49:21 +00006286 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00006287
Anders Carlsson59140b32009-08-28 03:16:11 +00006288 if (SS.isEmpty()) {
6289 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00006290 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00006291 }
Mike Stump11289f42009-09-09 15:08:12 +00006292
John McCall84d87672009-12-10 09:41:52 +00006293 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006294 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00006295 ForRedeclaration);
6296 Previous.setHideTags(false);
6297 if (S) {
6298 LookupName(Previous, S);
6299
6300 // It is really dumb that we have to do this.
6301 LookupResult::Filter F = Previous.makeFilter();
6302 while (F.hasNext()) {
6303 NamedDecl *D = F.next();
6304 if (!isDeclInScope(D, CurContext, S))
6305 F.erase();
6306 }
6307 F.done();
6308 } else {
6309 assert(IsInstantiation && "no scope in non-instantiation");
6310 assert(CurContext->isRecord() && "scope not record in instantiation");
6311 LookupQualifiedName(Previous, CurContext);
6312 }
6313
John McCall84d87672009-12-10 09:41:52 +00006314 // Check for invalid redeclarations.
6315 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6316 return 0;
6317
6318 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00006319 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6320 return 0;
6321
John McCall84c16cf2009-11-12 03:15:40 +00006322 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006323 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006324 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00006325 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00006326 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00006327 // FIXME: not all declaration name kinds are legal here
6328 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6329 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006330 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006331 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00006332 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006333 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6334 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00006335 }
John McCallb96ec562009-12-04 22:46:56 +00006336 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006337 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6338 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00006339 }
John McCallb96ec562009-12-04 22:46:56 +00006340 D->setAccess(AS);
6341 CurContext->addDecl(D);
6342
6343 if (!LookupContext) return D;
6344 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00006345
John McCall0b66eb32010-05-01 00:40:08 +00006346 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00006347 UD->setInvalidDecl();
6348 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00006349 }
6350
Sebastian Redl08905022011-02-05 19:23:19 +00006351 // Constructor inheriting using decls get special treatment.
6352 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00006353 if (CheckInheritedConstructorUsingDecl(UD))
6354 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00006355 return UD;
6356 }
6357
6358 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00006359
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006360 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00006361
John McCall3969e302009-12-08 07:46:18 +00006362 // Unlike most lookups, we don't always want to hide tag
6363 // declarations: tag names are visible through the using declaration
6364 // even if hidden by ordinary names, *except* in a dependent context
6365 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00006366 if (!IsInstantiation)
6367 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00006368
John McCall27b18f82009-11-17 02:14:36 +00006369 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00006370
John McCall9f3059a2009-10-09 21:13:30 +00006371 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00006372 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006373 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006374 UD->setInvalidDecl();
6375 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006376 }
6377
John McCallb96ec562009-12-04 22:46:56 +00006378 if (R.isAmbiguous()) {
6379 UD->setInvalidDecl();
6380 return UD;
6381 }
Mike Stump11289f42009-09-09 15:08:12 +00006382
John McCalle61f2ba2009-11-18 02:36:19 +00006383 if (IsTypeName) {
6384 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00006385 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006386 Diag(IdentLoc, diag::err_using_typename_non_type);
6387 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6388 Diag((*I)->getUnderlyingDecl()->getLocation(),
6389 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006390 UD->setInvalidDecl();
6391 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006392 }
6393 } else {
6394 // If we asked for a non-typename and we got a type, error out,
6395 // but only if this is an instantiation of an unresolved using
6396 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00006397 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006398 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6399 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006400 UD->setInvalidDecl();
6401 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006402 }
Anders Carlsson59140b32009-08-28 03:16:11 +00006403 }
6404
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006405 // C++0x N2914 [namespace.udecl]p6:
6406 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00006407 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006408 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6409 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006410 UD->setInvalidDecl();
6411 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006412 }
Mike Stump11289f42009-09-09 15:08:12 +00006413
John McCall84d87672009-12-10 09:41:52 +00006414 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6415 if (!CheckUsingShadowDecl(UD, *I, Previous))
6416 BuildUsingShadowDecl(S, UD, *I);
6417 }
John McCall3f746822009-11-17 05:59:44 +00006418
6419 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006420}
6421
Sebastian Redl08905022011-02-05 19:23:19 +00006422/// Additional checks for a using declaration referring to a constructor name.
6423bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6424 if (UD->isTypeName()) {
6425 // FIXME: Cannot specify typename when specifying constructor
6426 return true;
6427 }
6428
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006429 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006430 assert(SourceType &&
6431 "Using decl naming constructor doesn't have type in scope spec.");
6432 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6433
6434 // Check whether the named type is a direct base class.
6435 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6436 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6437 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6438 BaseIt != BaseE; ++BaseIt) {
6439 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6440 if (CanonicalSourceType == BaseType)
6441 break;
6442 }
6443
6444 if (BaseIt == BaseE) {
6445 // Did not find SourceType in the bases.
6446 Diag(UD->getUsingLocation(),
6447 diag::err_using_decl_constructor_not_in_direct_base)
6448 << UD->getNameInfo().getSourceRange()
6449 << QualType(SourceType, 0) << TargetClass;
6450 return true;
6451 }
6452
6453 BaseIt->setInheritConstructors();
6454
6455 return false;
6456}
6457
John McCall84d87672009-12-10 09:41:52 +00006458/// Checks that the given using declaration is not an invalid
6459/// redeclaration. Note that this is checking only for the using decl
6460/// itself, not for any ill-formedness among the UsingShadowDecls.
6461bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6462 bool isTypeName,
6463 const CXXScopeSpec &SS,
6464 SourceLocation NameLoc,
6465 const LookupResult &Prev) {
6466 // C++03 [namespace.udecl]p8:
6467 // C++0x [namespace.udecl]p10:
6468 // A using-declaration is a declaration and can therefore be used
6469 // repeatedly where (and only where) multiple declarations are
6470 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006471 //
John McCall032092f2010-11-29 18:01:58 +00006472 // That's in non-member contexts.
6473 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006474 return false;
6475
6476 NestedNameSpecifier *Qual
6477 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6478
6479 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6480 NamedDecl *D = *I;
6481
6482 bool DTypename;
6483 NestedNameSpecifier *DQual;
6484 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6485 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006486 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006487 } else if (UnresolvedUsingValueDecl *UD
6488 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6489 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006490 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006491 } else if (UnresolvedUsingTypenameDecl *UD
6492 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6493 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006494 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006495 } else continue;
6496
6497 // using decls differ if one says 'typename' and the other doesn't.
6498 // FIXME: non-dependent using decls?
6499 if (isTypeName != DTypename) continue;
6500
6501 // using decls differ if they name different scopes (but note that
6502 // template instantiation can cause this check to trigger when it
6503 // didn't before instantiation).
6504 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6505 Context.getCanonicalNestedNameSpecifier(DQual))
6506 continue;
6507
6508 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006509 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006510 return true;
6511 }
6512
6513 return false;
6514}
6515
John McCall3969e302009-12-08 07:46:18 +00006516
John McCallb96ec562009-12-04 22:46:56 +00006517/// Checks that the given nested-name qualifier used in a using decl
6518/// in the current context is appropriately related to the current
6519/// scope. If an error is found, diagnoses it and returns true.
6520bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6521 const CXXScopeSpec &SS,
6522 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006523 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006524
John McCall3969e302009-12-08 07:46:18 +00006525 if (!CurContext->isRecord()) {
6526 // C++03 [namespace.udecl]p3:
6527 // C++0x [namespace.udecl]p8:
6528 // A using-declaration for a class member shall be a member-declaration.
6529
6530 // If we weren't able to compute a valid scope, it must be a
6531 // dependent class scope.
6532 if (!NamedContext || NamedContext->isRecord()) {
6533 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6534 << SS.getRange();
6535 return true;
6536 }
6537
6538 // Otherwise, everything is known to be fine.
6539 return false;
6540 }
6541
6542 // The current scope is a record.
6543
6544 // If the named context is dependent, we can't decide much.
6545 if (!NamedContext) {
6546 // FIXME: in C++0x, we can diagnose if we can prove that the
6547 // nested-name-specifier does not refer to a base class, which is
6548 // still possible in some cases.
6549
6550 // Otherwise we have to conservatively report that things might be
6551 // okay.
6552 return false;
6553 }
6554
6555 if (!NamedContext->isRecord()) {
6556 // Ideally this would point at the last name in the specifier,
6557 // but we don't have that level of source info.
6558 Diag(SS.getRange().getBegin(),
6559 diag::err_using_decl_nested_name_specifier_is_not_class)
6560 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6561 return true;
6562 }
6563
Douglas Gregor7c842292010-12-21 07:41:49 +00006564 if (!NamedContext->isDependentContext() &&
6565 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6566 return true;
6567
John McCall3969e302009-12-08 07:46:18 +00006568 if (getLangOptions().CPlusPlus0x) {
6569 // C++0x [namespace.udecl]p3:
6570 // In a using-declaration used as a member-declaration, the
6571 // nested-name-specifier shall name a base class of the class
6572 // being defined.
6573
6574 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6575 cast<CXXRecordDecl>(NamedContext))) {
6576 if (CurContext == NamedContext) {
6577 Diag(NameLoc,
6578 diag::err_using_decl_nested_name_specifier_is_current_class)
6579 << SS.getRange();
6580 return true;
6581 }
6582
6583 Diag(SS.getRange().getBegin(),
6584 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6585 << (NestedNameSpecifier*) SS.getScopeRep()
6586 << cast<CXXRecordDecl>(CurContext)
6587 << SS.getRange();
6588 return true;
6589 }
6590
6591 return false;
6592 }
6593
6594 // C++03 [namespace.udecl]p4:
6595 // A using-declaration used as a member-declaration shall refer
6596 // to a member of a base class of the class being defined [etc.].
6597
6598 // Salient point: SS doesn't have to name a base class as long as
6599 // lookup only finds members from base classes. Therefore we can
6600 // diagnose here only if we can prove that that can't happen,
6601 // i.e. if the class hierarchies provably don't intersect.
6602
6603 // TODO: it would be nice if "definitely valid" results were cached
6604 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6605 // need to be repeated.
6606
6607 struct UserData {
6608 llvm::DenseSet<const CXXRecordDecl*> Bases;
6609
6610 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6611 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6612 Data->Bases.insert(Base);
6613 return true;
6614 }
6615
6616 bool hasDependentBases(const CXXRecordDecl *Class) {
6617 return !Class->forallBases(collect, this);
6618 }
6619
6620 /// Returns true if the base is dependent or is one of the
6621 /// accumulated base classes.
6622 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6623 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6624 return !Data->Bases.count(Base);
6625 }
6626
6627 bool mightShareBases(const CXXRecordDecl *Class) {
6628 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6629 }
6630 };
6631
6632 UserData Data;
6633
6634 // Returns false if we find a dependent base.
6635 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6636 return false;
6637
6638 // Returns false if the class has a dependent base or if it or one
6639 // of its bases is present in the base set of the current context.
6640 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6641 return false;
6642
6643 Diag(SS.getRange().getBegin(),
6644 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6645 << (NestedNameSpecifier*) SS.getScopeRep()
6646 << cast<CXXRecordDecl>(CurContext)
6647 << SS.getRange();
6648
6649 return true;
John McCallb96ec562009-12-04 22:46:56 +00006650}
6651
Richard Smithdda56e42011-04-15 14:24:37 +00006652Decl *Sema::ActOnAliasDeclaration(Scope *S,
6653 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006654 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006655 SourceLocation UsingLoc,
6656 UnqualifiedId &Name,
6657 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006658 // Skip up to the relevant declaration scope.
6659 while (S->getFlags() & Scope::TemplateParamScope)
6660 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006661 assert((S->getFlags() & Scope::DeclScope) &&
6662 "got alias-declaration outside of declaration scope");
6663
6664 if (Type.isInvalid())
6665 return 0;
6666
6667 bool Invalid = false;
6668 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6669 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006670 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006671
6672 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6673 return 0;
6674
6675 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006676 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006677 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006678 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6679 TInfo->getTypeLoc().getBeginLoc());
6680 }
Richard Smithdda56e42011-04-15 14:24:37 +00006681
6682 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6683 LookupName(Previous, S);
6684
6685 // Warn about shadowing the name of a template parameter.
6686 if (Previous.isSingleResult() &&
6687 Previous.getFoundDecl()->isTemplateParameter()) {
6688 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6689 Previous.getFoundDecl()))
6690 Invalid = true;
6691 Previous.clear();
6692 }
6693
6694 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6695 "name in alias declaration must be an identifier");
6696 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6697 Name.StartLocation,
6698 Name.Identifier, TInfo);
6699
6700 NewTD->setAccess(AS);
6701
6702 if (Invalid)
6703 NewTD->setInvalidDecl();
6704
Richard Smith3f1b5d02011-05-05 21:57:07 +00006705 CheckTypedefForVariablyModifiedType(S, NewTD);
6706 Invalid |= NewTD->isInvalidDecl();
6707
Richard Smithdda56e42011-04-15 14:24:37 +00006708 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006709
6710 NamedDecl *NewND;
6711 if (TemplateParamLists.size()) {
6712 TypeAliasTemplateDecl *OldDecl = 0;
6713 TemplateParameterList *OldTemplateParams = 0;
6714
6715 if (TemplateParamLists.size() != 1) {
6716 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6717 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6718 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6719 }
6720 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6721
6722 // Only consider previous declarations in the same scope.
6723 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6724 /*ExplicitInstantiationOrSpecialization*/false);
6725 if (!Previous.empty()) {
6726 Redeclaration = true;
6727
6728 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6729 if (!OldDecl && !Invalid) {
6730 Diag(UsingLoc, diag::err_redefinition_different_kind)
6731 << Name.Identifier;
6732
6733 NamedDecl *OldD = Previous.getRepresentativeDecl();
6734 if (OldD->getLocation().isValid())
6735 Diag(OldD->getLocation(), diag::note_previous_definition);
6736
6737 Invalid = true;
6738 }
6739
6740 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6741 if (TemplateParameterListsAreEqual(TemplateParams,
6742 OldDecl->getTemplateParameters(),
6743 /*Complain=*/true,
6744 TPL_TemplateMatch))
6745 OldTemplateParams = OldDecl->getTemplateParameters();
6746 else
6747 Invalid = true;
6748
6749 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6750 if (!Invalid &&
6751 !Context.hasSameType(OldTD->getUnderlyingType(),
6752 NewTD->getUnderlyingType())) {
6753 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6754 // but we can't reasonably accept it.
6755 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6756 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6757 if (OldTD->getLocation().isValid())
6758 Diag(OldTD->getLocation(), diag::note_previous_definition);
6759 Invalid = true;
6760 }
6761 }
6762 }
6763
6764 // Merge any previous default template arguments into our parameters,
6765 // and check the parameter list.
6766 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6767 TPC_TypeAliasTemplate))
6768 return 0;
6769
6770 TypeAliasTemplateDecl *NewDecl =
6771 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6772 Name.Identifier, TemplateParams,
6773 NewTD);
6774
6775 NewDecl->setAccess(AS);
6776
6777 if (Invalid)
6778 NewDecl->setInvalidDecl();
6779 else if (OldDecl)
6780 NewDecl->setPreviousDeclaration(OldDecl);
6781
6782 NewND = NewDecl;
6783 } else {
6784 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6785 NewND = NewTD;
6786 }
Richard Smithdda56e42011-04-15 14:24:37 +00006787
6788 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006789 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006790
Richard Smith3f1b5d02011-05-05 21:57:07 +00006791 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006792}
6793
John McCall48871652010-08-21 09:40:31 +00006794Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006795 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006796 SourceLocation AliasLoc,
6797 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006798 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006799 SourceLocation IdentLoc,
6800 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006801
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006802 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006803 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6804 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006805
Anders Carlssondca83c42009-03-28 06:23:46 +00006806 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006807 NamedDecl *PrevDecl
6808 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6809 ForRedeclaration);
6810 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6811 PrevDecl = 0;
6812
6813 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006814 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006815 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006816 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006817 // FIXME: At some point, we'll want to create the (redundant)
6818 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006819 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006820 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006821 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006822 }
Mike Stump11289f42009-09-09 15:08:12 +00006823
Anders Carlssondca83c42009-03-28 06:23:46 +00006824 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6825 diag::err_redefinition_different_kind;
6826 Diag(AliasLoc, DiagID) << Alias;
6827 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006828 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006829 }
6830
John McCall27b18f82009-11-17 02:14:36 +00006831 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006832 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006833
John McCall9f3059a2009-10-09 21:13:30 +00006834 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006835 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006836 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006837 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006838 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006839 }
Mike Stump11289f42009-09-09 15:08:12 +00006840
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006841 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006842 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006843 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006844 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006845
John McCalld8d0d432010-02-16 06:53:13 +00006846 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006847 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006848}
6849
Douglas Gregora57478e2010-05-01 15:04:51 +00006850namespace {
6851 /// \brief Scoped object used to handle the state changes required in Sema
6852 /// to implicitly define the body of a C++ member function;
6853 class ImplicitlyDefinedFunctionScope {
6854 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006855 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006856
6857 public:
6858 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006859 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006860 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006861 S.PushFunctionScope();
6862 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6863 }
6864
6865 ~ImplicitlyDefinedFunctionScope() {
6866 S.PopExpressionEvaluationContext();
6867 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00006868 }
6869 };
6870}
6871
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006872Sema::ImplicitExceptionSpecification
6873Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006874 // C++ [except.spec]p14:
6875 // An implicitly declared special member function (Clause 12) shall have an
6876 // exception-specification. [...]
6877 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006878 if (ClassDecl->isInvalidDecl())
6879 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006880
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006881 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006882 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6883 BEnd = ClassDecl->bases_end();
6884 B != BEnd; ++B) {
6885 if (B->isVirtual()) // Handled below.
6886 continue;
6887
Douglas Gregor9672f922010-07-03 00:47:00 +00006888 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6889 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006890 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6891 // If this is a deleted function, add it anyway. This might be conformant
6892 // with the standard. This might not. I'm not sure. It might not matter.
6893 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006894 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006895 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006896 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006897
6898 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006899 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6900 BEnd = ClassDecl->vbases_end();
6901 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00006902 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6903 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006904 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6905 // If this is a deleted function, add it anyway. This might be conformant
6906 // with the standard. This might not. I'm not sure. It might not matter.
6907 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006908 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006909 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006910 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006911
6912 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006913 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6914 FEnd = ClassDecl->field_end();
6915 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00006916 if (F->hasInClassInitializer()) {
6917 if (Expr *E = F->getInClassInitializer())
6918 ExceptSpec.CalledExpr(E);
6919 else if (!F->isInvalidDecl())
6920 ExceptSpec.SetDelayed();
6921 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00006922 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00006923 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6924 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6925 // If this is a deleted function, add it anyway. This might be conformant
6926 // with the standard. This might not. I'm not sure. It might not matter.
6927 // In particular, the problem is that this function never gets called. It
6928 // might just be ill-formed because this function attempts to refer to
6929 // a deleted function here.
6930 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006931 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006932 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006933 }
John McCalldb40c7f2010-12-14 08:05:40 +00006934
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006935 return ExceptSpec;
6936}
6937
6938CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6939 CXXRecordDecl *ClassDecl) {
6940 // C++ [class.ctor]p5:
6941 // A default constructor for a class X is a constructor of class X
6942 // that can be called without an argument. If there is no
6943 // user-declared constructor for class X, a default constructor is
6944 // implicitly declared. An implicitly-declared default constructor
6945 // is an inline public member of its class.
6946 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6947 "Should not build implicit default constructor!");
6948
6949 ImplicitExceptionSpecification Spec =
6950 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6951 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00006952
Douglas Gregor6d880b12010-07-01 22:31:05 +00006953 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006954 CanQualType ClassType
6955 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006956 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006957 DeclarationName Name
6958 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006959 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006960 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00006961 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006962 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006963 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006964 /*TInfo=*/0,
6965 /*isExplicit=*/false,
6966 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00006967 /*isImplicitlyDeclared=*/true,
6968 // FIXME: apply the rules for definitions here
6969 /*isConstexpr=*/false);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006970 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00006971 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006972 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00006973 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00006974
6975 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00006976 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6977
Douglas Gregor0be31a22010-07-02 17:43:08 +00006978 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00006979 PushOnScopeChains(DefaultCon, S, false);
6980 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00006981
6982 if (ShouldDeleteDefaultConstructor(DefaultCon))
6983 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00006984
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006985 return DefaultCon;
6986}
6987
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006988void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6989 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006990 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006991 !Constructor->doesThisDeclarationHaveABody() &&
6992 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006993 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006994
Anders Carlsson423f5d82010-04-23 16:04:08 +00006995 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006996 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006997
Douglas Gregora57478e2010-05-01 15:04:51 +00006998 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006999 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00007000 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007001 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007002 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007003 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00007004 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00007005 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00007006 }
Douglas Gregor73193272010-09-20 16:48:21 +00007007
7008 SourceLocation Loc = Constructor->getLocation();
7009 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7010
7011 Constructor->setUsed();
7012 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007013
7014 if (ASTMutationListener *L = getASTMutationListener()) {
7015 L->CompletedImplicitDefinition(Constructor);
7016 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007017}
7018
Richard Smith938f40b2011-06-11 17:19:42 +00007019/// Get any existing defaulted default constructor for the given class. Do not
7020/// implicitly define one if it does not exist.
7021static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7022 CXXRecordDecl *D) {
7023 ASTContext &Context = Self.Context;
7024 QualType ClassType = Context.getTypeDeclType(D);
7025 DeclarationName ConstructorName
7026 = Context.DeclarationNames.getCXXConstructorName(
7027 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7028
7029 DeclContext::lookup_const_iterator Con, ConEnd;
7030 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7031 Con != ConEnd; ++Con) {
7032 // A function template cannot be defaulted.
7033 if (isa<FunctionTemplateDecl>(*Con))
7034 continue;
7035
7036 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7037 if (Constructor->isDefaultConstructor())
7038 return Constructor->isDefaulted() ? Constructor : 0;
7039 }
7040 return 0;
7041}
7042
7043void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7044 if (!D) return;
7045 AdjustDeclIfTemplate(D);
7046
7047 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7048 CXXConstructorDecl *CtorDecl
7049 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7050
7051 if (!CtorDecl) return;
7052
7053 // Compute the exception specification for the default constructor.
7054 const FunctionProtoType *CtorTy =
7055 CtorDecl->getType()->castAs<FunctionProtoType>();
7056 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7057 ImplicitExceptionSpecification Spec =
7058 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7059 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7060 assert(EPI.ExceptionSpecType != EST_Delayed);
7061
7062 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7063 }
7064
7065 // If the default constructor is explicitly defaulted, checking the exception
7066 // specification is deferred until now.
7067 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7068 !ClassDecl->isDependentType())
7069 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7070}
7071
Sebastian Redl08905022011-02-05 19:23:19 +00007072void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7073 // We start with an initial pass over the base classes to collect those that
7074 // inherit constructors from. If there are none, we can forgo all further
7075 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007076 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00007077 BasesVector BasesToInheritFrom;
7078 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7079 BaseE = ClassDecl->bases_end();
7080 BaseIt != BaseE; ++BaseIt) {
7081 if (BaseIt->getInheritConstructors()) {
7082 QualType Base = BaseIt->getType();
7083 if (Base->isDependentType()) {
7084 // If we inherit constructors from anything that is dependent, just
7085 // abort processing altogether. We'll get another chance for the
7086 // instantiations.
7087 return;
7088 }
7089 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7090 }
7091 }
7092 if (BasesToInheritFrom.empty())
7093 return;
7094
7095 // Now collect the constructors that we already have in the current class.
7096 // Those take precedence over inherited constructors.
7097 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7098 // unless there is a user-declared constructor with the same signature in
7099 // the class where the using-declaration appears.
7100 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7101 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7102 CtorE = ClassDecl->ctor_end();
7103 CtorIt != CtorE; ++CtorIt) {
7104 ExistingConstructors.insert(
7105 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7106 }
7107
7108 Scope *S = getScopeForContext(ClassDecl);
7109 DeclarationName CreatedCtorName =
7110 Context.DeclarationNames.getCXXConstructorName(
7111 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7112
7113 // Now comes the true work.
7114 // First, we keep a map from constructor types to the base that introduced
7115 // them. Needed for finding conflicting constructors. We also keep the
7116 // actually inserted declarations in there, for pretty diagnostics.
7117 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7118 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7119 ConstructorToSourceMap InheritedConstructors;
7120 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7121 BaseE = BasesToInheritFrom.end();
7122 BaseIt != BaseE; ++BaseIt) {
7123 const RecordType *Base = *BaseIt;
7124 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7125 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7126 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7127 CtorE = BaseDecl->ctor_end();
7128 CtorIt != CtorE; ++CtorIt) {
7129 // Find the using declaration for inheriting this base's constructors.
7130 DeclarationName Name =
7131 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7132 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7133 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7134 SourceLocation UsingLoc = UD ? UD->getLocation() :
7135 ClassDecl->getLocation();
7136
7137 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7138 // from the class X named in the using-declaration consists of actual
7139 // constructors and notional constructors that result from the
7140 // transformation of defaulted parameters as follows:
7141 // - all non-template default constructors of X, and
7142 // - for each non-template constructor of X that has at least one
7143 // parameter with a default argument, the set of constructors that
7144 // results from omitting any ellipsis parameter specification and
7145 // successively omitting parameters with a default argument from the
7146 // end of the parameter-type-list.
7147 CXXConstructorDecl *BaseCtor = *CtorIt;
7148 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7149 const FunctionProtoType *BaseCtorType =
7150 BaseCtor->getType()->getAs<FunctionProtoType>();
7151
7152 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7153 maxParams = BaseCtor->getNumParams();
7154 params <= maxParams; ++params) {
7155 // Skip default constructors. They're never inherited.
7156 if (params == 0)
7157 continue;
7158 // Skip copy and move constructors for the same reason.
7159 if (CanBeCopyOrMove && params == 1)
7160 continue;
7161
7162 // Build up a function type for this particular constructor.
7163 // FIXME: The working paper does not consider that the exception spec
7164 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00007165 // source. This code doesn't yet, either. When it does, this code will
7166 // need to be delayed until after exception specifications and in-class
7167 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00007168 const Type *NewCtorType;
7169 if (params == maxParams)
7170 NewCtorType = BaseCtorType;
7171 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007172 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00007173 for (unsigned i = 0; i < params; ++i) {
7174 Args.push_back(BaseCtorType->getArgType(i));
7175 }
7176 FunctionProtoType::ExtProtoInfo ExtInfo =
7177 BaseCtorType->getExtProtoInfo();
7178 ExtInfo.Variadic = false;
7179 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7180 Args.data(), params, ExtInfo)
7181 .getTypePtr();
7182 }
7183 const Type *CanonicalNewCtorType =
7184 Context.getCanonicalType(NewCtorType);
7185
7186 // Now that we have the type, first check if the class already has a
7187 // constructor with this signature.
7188 if (ExistingConstructors.count(CanonicalNewCtorType))
7189 continue;
7190
7191 // Then we check if we have already declared an inherited constructor
7192 // with this signature.
7193 std::pair<ConstructorToSourceMap::iterator, bool> result =
7194 InheritedConstructors.insert(std::make_pair(
7195 CanonicalNewCtorType,
7196 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7197 if (!result.second) {
7198 // Already in the map. If it came from a different class, that's an
7199 // error. Not if it's from the same.
7200 CanQualType PreviousBase = result.first->second.first;
7201 if (CanonicalBase != PreviousBase) {
7202 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7203 const CXXConstructorDecl *PrevBaseCtor =
7204 PrevCtor->getInheritedConstructor();
7205 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7206
7207 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7208 Diag(BaseCtor->getLocation(),
7209 diag::note_using_decl_constructor_conflict_current_ctor);
7210 Diag(PrevBaseCtor->getLocation(),
7211 diag::note_using_decl_constructor_conflict_previous_ctor);
7212 Diag(PrevCtor->getLocation(),
7213 diag::note_using_decl_constructor_conflict_previous_using);
7214 }
7215 continue;
7216 }
7217
7218 // OK, we're there, now add the constructor.
7219 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00007220 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00007221 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7222 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00007223 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7224 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007225 /*ImplicitlyDeclared=*/true,
7226 // FIXME: Due to a defect in the standard, we treat inherited
7227 // constructors as constexpr even if that makes them ill-formed.
7228 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00007229 NewCtor->setAccess(BaseCtor->getAccess());
7230
7231 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007232 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00007233 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007234 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7235 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00007236 /*IdentifierInfo=*/0,
7237 BaseCtorType->getArgType(i),
7238 /*TInfo=*/0, SC_None,
7239 SC_None, /*DefaultArg=*/0));
7240 }
David Blaikie9c70e042011-09-21 18:16:56 +00007241 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00007242 NewCtor->setInheritedConstructor(BaseCtor);
7243
7244 PushOnScopeChains(NewCtor, S, false);
7245 ClassDecl->addDecl(NewCtor);
7246 result.first->second.second = NewCtor;
7247 }
7248 }
7249 }
7250}
7251
Alexis Huntf91729462011-05-12 22:46:25 +00007252Sema::ImplicitExceptionSpecification
7253Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00007254 // C++ [except.spec]p14:
7255 // An implicitly declared special member function (Clause 12) shall have
7256 // an exception-specification.
7257 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007258 if (ClassDecl->isInvalidDecl())
7259 return ExceptSpec;
7260
Douglas Gregorf1203042010-07-01 19:09:28 +00007261 // Direct base-class destructors.
7262 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7263 BEnd = ClassDecl->bases_end();
7264 B != BEnd; ++B) {
7265 if (B->isVirtual()) // Handled below.
7266 continue;
7267
7268 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7269 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007270 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007271 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007272
Douglas Gregorf1203042010-07-01 19:09:28 +00007273 // Virtual base-class destructors.
7274 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7275 BEnd = ClassDecl->vbases_end();
7276 B != BEnd; ++B) {
7277 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7278 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007279 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007280 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007281
Douglas Gregorf1203042010-07-01 19:09:28 +00007282 // Field destructors.
7283 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7284 FEnd = ClassDecl->field_end();
7285 F != FEnd; ++F) {
7286 if (const RecordType *RecordTy
7287 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7288 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007289 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007290 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007291
Alexis Huntf91729462011-05-12 22:46:25 +00007292 return ExceptSpec;
7293}
7294
7295CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7296 // C++ [class.dtor]p2:
7297 // If a class has no user-declared destructor, a destructor is
7298 // declared implicitly. An implicitly-declared destructor is an
7299 // inline public member of its class.
7300
7301 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00007302 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00007303 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7304
Douglas Gregor7454c562010-07-02 20:37:36 +00007305 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00007306 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007307
Douglas Gregorf1203042010-07-01 19:09:28 +00007308 CanQualType ClassType
7309 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007310 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00007311 DeclarationName Name
7312 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007313 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00007314 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007315 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7316 /*isInline=*/true,
7317 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00007318 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00007319 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00007320 Destructor->setImplicit();
7321 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00007322
7323 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00007324 ++ASTContext::NumImplicitDestructorsDeclared;
7325
7326 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007327 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00007328 PushOnScopeChains(Destructor, S, false);
7329 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00007330
7331 // This could be uniqued if it ever proves significant.
7332 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00007333
7334 if (ShouldDeleteDestructor(Destructor))
7335 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00007336
7337 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00007338
Douglas Gregorf1203042010-07-01 19:09:28 +00007339 return Destructor;
7340}
7341
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007342void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00007343 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007344 assert((Destructor->isDefaulted() &&
7345 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007346 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00007347 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007348 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007349
Douglas Gregor54818f02010-05-12 16:39:35 +00007350 if (Destructor->isInvalidDecl())
7351 return;
7352
Douglas Gregora57478e2010-05-01 15:04:51 +00007353 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007354
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007355 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00007356 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7357 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00007358
Douglas Gregor54818f02010-05-12 16:39:35 +00007359 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007360 Diag(CurrentLocation, diag::note_member_synthesized_at)
7361 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7362
7363 Destructor->setInvalidDecl();
7364 return;
7365 }
7366
Douglas Gregor73193272010-09-20 16:48:21 +00007367 SourceLocation Loc = Destructor->getLocation();
7368 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00007369 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007370 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007371 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007372
7373 if (ASTMutationListener *L = getASTMutationListener()) {
7374 L->CompletedImplicitDefinition(Destructor);
7375 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007376}
7377
Sebastian Redl623ea822011-05-19 05:13:44 +00007378void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7379 CXXDestructorDecl *destructor) {
7380 // C++11 [class.dtor]p3:
7381 // A declaration of a destructor that does not have an exception-
7382 // specification is implicitly considered to have the same exception-
7383 // specification as an implicit declaration.
7384 const FunctionProtoType *dtorType = destructor->getType()->
7385 getAs<FunctionProtoType>();
7386 if (dtorType->hasExceptionSpec())
7387 return;
7388
7389 ImplicitExceptionSpecification exceptSpec =
7390 ComputeDefaultedDtorExceptionSpec(classDecl);
7391
Chandler Carruth9a797572011-09-20 04:55:26 +00007392 // Replace the destructor's type, building off the existing one. Fortunately,
7393 // the only thing of interest in the destructor type is its extended info.
7394 // The return and arguments are fixed.
7395 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00007396 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7397 epi.NumExceptions = exceptSpec.size();
7398 epi.Exceptions = exceptSpec.data();
7399 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7400
7401 destructor->setType(ty);
7402
7403 // FIXME: If the destructor has a body that could throw, and the newly created
7404 // spec doesn't allow exceptions, we should emit a warning, because this
7405 // change in behavior can break conforming C++03 programs at runtime.
7406 // However, we don't have a body yet, so it needs to be done somewhere else.
7407}
7408
Sebastian Redl22653ba2011-08-30 19:58:05 +00007409/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00007410/// \c To.
7411///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007412/// This routine is used to copy/move the members of a class with an
7413/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00007414/// copied are arrays, this routine builds for loops to copy them.
7415///
7416/// \param S The Sema object used for type-checking.
7417///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007418/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007419///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007420/// \param T The type of the expressions being copied/moved. Both expressions
7421/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007422///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007423/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007424///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007425/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007426///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007427/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007428/// Otherwise, it's a non-static member subobject.
7429///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007430/// \param Copying Whether we're copying or moving.
7431///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007432/// \param Depth Internal parameter recording the depth of the recursion.
7433///
7434/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007435static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007436BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007437 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007438 bool CopyingBaseSubobject, bool Copying,
7439 unsigned Depth = 0) {
7440 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007441 // Each subobject is assigned in the manner appropriate to its type:
7442 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007443 // - if the subobject is of class type, as if by a call to operator= with
7444 // the subobject as the object expression and the corresponding
7445 // subobject of x as a single function argument (as if by explicit
7446 // qualification; that is, ignoring any possible virtual overriding
7447 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007448 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7449 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7450
7451 // Look for operator=.
7452 DeclarationName Name
7453 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7454 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7455 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7456
Sebastian Redl22653ba2011-08-30 19:58:05 +00007457 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007458 LookupResult::Filter F = OpLookup.makeFilter();
7459 while (F.hasNext()) {
7460 NamedDecl *D = F.next();
7461 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007462 if (Copying ? Method->isCopyAssignmentOperator() :
7463 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007464 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007465
Douglas Gregorb139cd52010-05-01 20:49:11 +00007466 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007467 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007468 F.done();
7469
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007470 // Suppress the protected check (C++ [class.protected]) for each of the
7471 // assignment operators we found. This strange dance is required when
7472 // we're assigning via a base classes's copy-assignment operator. To
7473 // ensure that we're getting the right base class subobject (without
7474 // ambiguities), we need to cast "this" to that subobject type; to
7475 // ensure that we don't go through the virtual call mechanism, we need
7476 // to qualify the operator= name with the base class (see below). However,
7477 // this means that if the base class has a protected copy assignment
7478 // operator, the protected member access check will fail. So, we
7479 // rewrite "protected" access to "public" access in this case, since we
7480 // know by construction that we're calling from a derived class.
7481 if (CopyingBaseSubobject) {
7482 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7483 L != LEnd; ++L) {
7484 if (L.getAccess() == AS_protected)
7485 L.setAccess(AS_public);
7486 }
7487 }
7488
Douglas Gregorb139cd52010-05-01 20:49:11 +00007489 // Create the nested-name-specifier that will be used to qualify the
7490 // reference to operator=; this is required to suppress the virtual
7491 // call mechanism.
7492 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00007493 SS.MakeTrivial(S.Context,
7494 NestedNameSpecifier::Create(S.Context, 0, false,
7495 T.getTypePtr()),
7496 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007497
7498 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007499 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007500 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007501 /*FirstQualifierInScope=*/0, OpLookup,
7502 /*TemplateArgs=*/0,
7503 /*SuppressQualifierCheck=*/true);
7504 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007505 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007506
7507 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007508
John McCalldadc5752010-08-24 06:29:42 +00007509 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007510 OpEqualRef.takeAs<Expr>(),
7511 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007512 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007513 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007514
7515 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007516 }
John McCallab8c2732010-03-16 06:11:48 +00007517
Douglas Gregorb139cd52010-05-01 20:49:11 +00007518 // - if the subobject is of scalar type, the built-in assignment
7519 // operator is used.
7520 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7521 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007522 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007523 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007524 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007525
7526 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007527 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007528
7529 // - if the subobject is an array, each element is assigned, in the
7530 // manner appropriate to the element type;
7531
7532 // Construct a loop over the array bounds, e.g.,
7533 //
7534 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7535 //
7536 // that will copy each of the array elements.
7537 QualType SizeType = S.Context.getSizeType();
7538
7539 // Create the iteration variable.
7540 IdentifierInfo *IterationVarName = 0;
7541 {
7542 llvm::SmallString<8> Str;
7543 llvm::raw_svector_ostream OS(Str);
7544 OS << "__i" << Depth;
7545 IterationVarName = &S.Context.Idents.get(OS.str());
7546 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007547 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007548 IterationVarName, SizeType,
7549 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007550 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007551
7552 // Initialize the iteration variable to zero.
7553 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007554 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007555
7556 // Create a reference to the iteration variable; we'll use this several
7557 // times throughout.
7558 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00007559 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007560 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7561
7562 // Create the DeclStmt that holds the iteration variable.
7563 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7564
7565 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007566 llvm::APInt Upper
7567 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007568 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00007569 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00007570 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7571 BO_NE, S.Context.BoolTy,
7572 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007573
7574 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007575 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007576 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7577 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007578
7579 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007580 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7581 IterationVarRef, Loc));
7582 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7583 IterationVarRef, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007584 if (!Copying) // Cast to rvalue
7585 From = CastForMoving(S, From);
7586
7587 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007588 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7589 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007590 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007591 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007592 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007593
7594 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007595 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007596 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007597 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007598 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007599}
7600
Alexis Hunt119f3652011-05-14 05:23:20 +00007601std::pair<Sema::ImplicitExceptionSpecification, bool>
7602Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7603 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007604 if (ClassDecl->isInvalidDecl())
7605 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7606
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007607 // C++ [class.copy]p10:
7608 // If the class definition does not explicitly declare a copy
7609 // assignment operator, one is declared implicitly.
7610 // The implicitly-defined copy assignment operator for a class X
7611 // will have the form
7612 //
7613 // X& X::operator=(const X&)
7614 //
7615 // if
7616 bool HasConstCopyAssignment = true;
7617
7618 // -- each direct base class B of X has a copy assignment operator
7619 // whose parameter is of type const B&, const volatile B& or B,
7620 // and
7621 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7622 BaseEnd = ClassDecl->bases_end();
7623 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007624 // We'll handle this below
7625 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7626 continue;
7627
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007628 assert(!Base->getType()->isDependentType() &&
7629 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007630 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7631 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7632 &HasConstCopyAssignment);
7633 }
7634
7635 // In C++0x, the above citation has "or virtual added"
7636 if (LangOpts.CPlusPlus0x) {
7637 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7638 BaseEnd = ClassDecl->vbases_end();
7639 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7640 assert(!Base->getType()->isDependentType() &&
7641 "Cannot generate implicit members for class with dependent bases.");
7642 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7643 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7644 &HasConstCopyAssignment);
7645 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007646 }
7647
7648 // -- for all the nonstatic data members of X that are of a class
7649 // type M (or array thereof), each such class type has a copy
7650 // assignment operator whose parameter is of type const M&,
7651 // const volatile M& or M.
7652 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7653 FieldEnd = ClassDecl->field_end();
7654 HasConstCopyAssignment && Field != FieldEnd;
7655 ++Field) {
7656 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007657 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7658 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7659 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007660 }
7661 }
7662
7663 // Otherwise, the implicitly declared copy assignment operator will
7664 // have the form
7665 //
7666 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007667
Douglas Gregor68e11362010-07-01 17:48:08 +00007668 // C++ [except.spec]p14:
7669 // An implicitly declared special member function (Clause 12) shall have an
7670 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007671
7672 // It is unspecified whether or not an implicit copy assignment operator
7673 // attempts to deduplicate calls to assignment operators of virtual bases are
7674 // made. As such, this exception specification is effectively unspecified.
7675 // Based on a similar decision made for constness in C++0x, we're erring on
7676 // the side of assuming such calls to be made regardless of whether they
7677 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007678 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007679 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007680 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7681 BaseEnd = ClassDecl->bases_end();
7682 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007683 if (Base->isVirtual())
7684 continue;
7685
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007686 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007687 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007688 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7689 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007690 ExceptSpec.CalledDecl(CopyAssign);
7691 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007692
7693 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7694 BaseEnd = ClassDecl->vbases_end();
7695 Base != BaseEnd; ++Base) {
7696 CXXRecordDecl *BaseClassDecl
7697 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7698 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7699 ArgQuals, false, 0))
7700 ExceptSpec.CalledDecl(CopyAssign);
7701 }
7702
Douglas Gregor68e11362010-07-01 17:48:08 +00007703 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7704 FieldEnd = ClassDecl->field_end();
7705 Field != FieldEnd;
7706 ++Field) {
7707 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007708 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7709 if (CXXMethodDecl *CopyAssign =
7710 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7711 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007712 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007713 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007714
Alexis Hunt119f3652011-05-14 05:23:20 +00007715 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7716}
7717
7718CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7719 // Note: The following rules are largely analoguous to the copy
7720 // constructor rules. Note that virtual bases are not taken into account
7721 // for determining the argument type of the operator. Note also that
7722 // operators taking an object instead of a reference are allowed.
7723
7724 ImplicitExceptionSpecification Spec(Context);
7725 bool Const;
7726 llvm::tie(Spec, Const) =
7727 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7728
7729 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7730 QualType RetType = Context.getLValueReferenceType(ArgType);
7731 if (Const)
7732 ArgType = ArgType.withConst();
7733 ArgType = Context.getLValueReferenceType(ArgType);
7734
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007735 // An implicitly-declared copy assignment operator is an inline public
7736 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007737 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007738 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007739 SourceLocation ClassLoc = ClassDecl->getLocation();
7740 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007741 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007742 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007743 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007744 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007745 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007746 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007747 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007748 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007749 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007750 CopyAssignment->setImplicit();
7751 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007752
7753 // Add the parameter to the operator.
7754 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007755 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007756 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007757 SC_None,
7758 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007759 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007760
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007761 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007762 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007763
Douglas Gregor0be31a22010-07-02 17:43:08 +00007764 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007765 PushOnScopeChains(CopyAssignment, S, false);
7766 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007767
Alexis Huntd74c85f2011-06-22 01:05:13 +00007768 // C++0x [class.copy]p18:
7769 // ... If the class definition declares a move constructor or move
7770 // assignment operator, the implicitly declared copy assignment operator is
7771 // defined as deleted; ...
7772 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7773 ClassDecl->hasUserDeclaredMoveAssignment() ||
7774 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007775 CopyAssignment->setDeletedAsWritten();
7776
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007777 AddOverriddenMethods(ClassDecl, CopyAssignment);
7778 return CopyAssignment;
7779}
7780
Douglas Gregorb139cd52010-05-01 20:49:11 +00007781void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7782 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007783 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007784 CopyAssignOperator->isOverloadedOperator() &&
7785 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007786 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007787 "DefineImplicitCopyAssignment called for wrong function");
7788
7789 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7790
7791 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7792 CopyAssignOperator->setInvalidDecl();
7793 return;
7794 }
7795
7796 CopyAssignOperator->setUsed();
7797
7798 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007799 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007800
7801 // C++0x [class.copy]p30:
7802 // The implicitly-defined or explicitly-defaulted copy assignment operator
7803 // for a non-union class X performs memberwise copy assignment of its
7804 // subobjects. The direct base classes of X are assigned first, in the
7805 // order of their declaration in the base-specifier-list, and then the
7806 // immediate non-static data members of X are assigned, in the order in
7807 // which they were declared in the class definition.
7808
7809 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007810 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007811
7812 // The parameter for the "other" object, which we are copying from.
7813 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7814 Qualifiers OtherQuals = Other->getType().getQualifiers();
7815 QualType OtherRefType = Other->getType();
7816 if (const LValueReferenceType *OtherRef
7817 = OtherRefType->getAs<LValueReferenceType>()) {
7818 OtherRefType = OtherRef->getPointeeType();
7819 OtherQuals = OtherRefType.getQualifiers();
7820 }
7821
7822 // Our location for everything implicitly-generated.
7823 SourceLocation Loc = CopyAssignOperator->getLocation();
7824
7825 // Construct a reference to the "other" object. We'll be using this
7826 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007827 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007828 assert(OtherRef && "Reference to parameter cannot fail!");
7829
7830 // Construct the "this" pointer. We'll be using this throughout the generated
7831 // ASTs.
7832 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7833 assert(This && "Reference to this cannot fail!");
7834
7835 // Assign base classes.
7836 bool Invalid = false;
7837 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7838 E = ClassDecl->bases_end(); Base != E; ++Base) {
7839 // Form the assignment:
7840 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7841 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007842 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007843 Invalid = true;
7844 continue;
7845 }
7846
John McCallcf142162010-08-07 06:22:56 +00007847 CXXCastPath BasePath;
7848 BasePath.push_back(Base);
7849
Douglas Gregorb139cd52010-05-01 20:49:11 +00007850 // Construct the "from" expression, which is an implicit cast to the
7851 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007852 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007853 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7854 CK_UncheckedDerivedToBase,
7855 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007856
7857 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007858 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007859
7860 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007861 To = ImpCastExprToType(To.take(),
7862 Context.getCVRQualifiedType(BaseType,
7863 CopyAssignOperator->getTypeQualifiers()),
7864 CK_UncheckedDerivedToBase,
7865 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007866
7867 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007868 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007869 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007870 /*CopyingBaseSubobject=*/true,
7871 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007872 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007873 Diag(CurrentLocation, diag::note_member_synthesized_at)
7874 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7875 CopyAssignOperator->setInvalidDecl();
7876 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007877 }
7878
7879 // Success! Record the copy.
7880 Statements.push_back(Copy.takeAs<Expr>());
7881 }
7882
7883 // \brief Reference to the __builtin_memcpy function.
7884 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007885 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007886 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007887
7888 // Assign non-static members.
7889 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7890 FieldEnd = ClassDecl->field_end();
7891 Field != FieldEnd; ++Field) {
7892 // Check for members of reference type; we can't copy those.
7893 if (Field->getType()->isReferenceType()) {
7894 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7895 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7896 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007897 Diag(CurrentLocation, diag::note_member_synthesized_at)
7898 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007899 Invalid = true;
7900 continue;
7901 }
7902
7903 // Check for members of const-qualified, non-class type.
7904 QualType BaseType = Context.getBaseElementType(Field->getType());
7905 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7906 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7907 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7908 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007909 Diag(CurrentLocation, diag::note_member_synthesized_at)
7910 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007911 Invalid = true;
7912 continue;
7913 }
John McCall1b1a1db2011-06-17 00:18:42 +00007914
7915 // Suppress assigning zero-width bitfields.
7916 if (const Expr *Width = Field->getBitWidth())
7917 if (Width->EvaluateAsInt(Context) == 0)
7918 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007919
7920 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007921 if (FieldType->isIncompleteArrayType()) {
7922 assert(ClassDecl->hasFlexibleArrayMember() &&
7923 "Incomplete array type is not valid");
7924 continue;
7925 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007926
7927 // Build references to the field in the object we're copying from and to.
7928 CXXScopeSpec SS; // Intentionally empty
7929 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7930 LookupMemberName);
7931 MemberLookup.addDecl(*Field);
7932 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00007933 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00007934 Loc, /*IsArrow=*/false,
7935 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00007936 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00007937 Loc, /*IsArrow=*/true,
7938 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007939 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7940 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7941
7942 // If the field should be copied with __builtin_memcpy rather than via
7943 // explicit assignments, do so. This optimization only applies for arrays
7944 // of scalars and arrays of class type with trivial copy-assignment
7945 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00007946 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00007947 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007948 // Compute the size of the memory buffer to be copied.
7949 QualType SizeType = Context.getSizeType();
7950 llvm::APInt Size(Context.getTypeSize(SizeType),
7951 Context.getTypeSizeInChars(BaseType).getQuantity());
7952 for (const ConstantArrayType *Array
7953 = Context.getAsConstantArrayType(FieldType);
7954 Array;
7955 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00007956 llvm::APInt ArraySize
7957 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007958 Size *= ArraySize;
7959 }
7960
7961 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00007962 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7963 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007964
7965 bool NeedsCollectableMemCpy =
7966 (BaseType->isRecordType() &&
7967 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7968
7969 if (NeedsCollectableMemCpy) {
7970 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007971 // Create a reference to the __builtin_objc_memmove_collectable function.
7972 LookupResult R(*this,
7973 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007974 Loc, LookupOrdinaryName);
7975 LookupName(R, TUScope, true);
7976
7977 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7978 if (!CollectableMemCpy) {
7979 // Something went horribly wrong earlier, and we will have
7980 // complained about it.
7981 Invalid = true;
7982 continue;
7983 }
7984
7985 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7986 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007987 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007988 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7989 }
7990 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007991 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007992 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007993 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7994 LookupOrdinaryName);
7995 LookupName(R, TUScope, true);
7996
7997 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7998 if (!BuiltinMemCpy) {
7999 // Something went horribly wrong earlier, and we will have complained
8000 // about it.
8001 Invalid = true;
8002 continue;
8003 }
8004
8005 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8006 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008007 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008008 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8009 }
8010
John McCall37ad5512010-08-23 06:44:23 +00008011 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008012 CallArgs.push_back(To.takeAs<Expr>());
8013 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008014 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00008015 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008016 if (NeedsCollectableMemCpy)
8017 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008018 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008019 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008020 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008021 else
8022 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008023 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008024 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008025 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008026
Douglas Gregorb139cd52010-05-01 20:49:11 +00008027 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8028 Statements.push_back(Call.takeAs<Expr>());
8029 continue;
8030 }
8031
8032 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00008033 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008034 To.get(), From.get(),
8035 /*CopyingBaseSubobject=*/false,
8036 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008037 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008038 Diag(CurrentLocation, diag::note_member_synthesized_at)
8039 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8040 CopyAssignOperator->setInvalidDecl();
8041 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008042 }
8043
8044 // Success! Record the copy.
8045 Statements.push_back(Copy.takeAs<Stmt>());
8046 }
8047
8048 if (!Invalid) {
8049 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00008050 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008051
John McCalldadc5752010-08-24 06:29:42 +00008052 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008053 if (Return.isInvalid())
8054 Invalid = true;
8055 else {
8056 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00008057
8058 if (Trap.hasErrorOccurred()) {
8059 Diag(CurrentLocation, diag::note_member_synthesized_at)
8060 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8061 Invalid = true;
8062 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008063 }
8064 }
8065
8066 if (Invalid) {
8067 CopyAssignOperator->setInvalidDecl();
8068 return;
8069 }
8070
John McCalldadc5752010-08-24 06:29:42 +00008071 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00008072 /*isStmtExpr=*/false);
8073 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8074 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00008075
8076 if (ASTMutationListener *L = getASTMutationListener()) {
8077 L->CompletedImplicitDefinition(CopyAssignOperator);
8078 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008079}
8080
Sebastian Redl22653ba2011-08-30 19:58:05 +00008081Sema::ImplicitExceptionSpecification
8082Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8083 ImplicitExceptionSpecification ExceptSpec(Context);
8084
8085 if (ClassDecl->isInvalidDecl())
8086 return ExceptSpec;
8087
8088 // C++0x [except.spec]p14:
8089 // An implicitly declared special member function (Clause 12) shall have an
8090 // exception-specification. [...]
8091
8092 // It is unspecified whether or not an implicit move assignment operator
8093 // attempts to deduplicate calls to assignment operators of virtual bases are
8094 // made. As such, this exception specification is effectively unspecified.
8095 // Based on a similar decision made for constness in C++0x, we're erring on
8096 // the side of assuming such calls to be made regardless of whether they
8097 // actually happen.
8098 // Note that a move constructor is not implicitly declared when there are
8099 // virtual bases, but it can still be user-declared and explicitly defaulted.
8100 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8101 BaseEnd = ClassDecl->bases_end();
8102 Base != BaseEnd; ++Base) {
8103 if (Base->isVirtual())
8104 continue;
8105
8106 CXXRecordDecl *BaseClassDecl
8107 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8108 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8109 false, 0))
8110 ExceptSpec.CalledDecl(MoveAssign);
8111 }
8112
8113 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8114 BaseEnd = ClassDecl->vbases_end();
8115 Base != BaseEnd; ++Base) {
8116 CXXRecordDecl *BaseClassDecl
8117 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8118 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8119 false, 0))
8120 ExceptSpec.CalledDecl(MoveAssign);
8121 }
8122
8123 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8124 FieldEnd = ClassDecl->field_end();
8125 Field != FieldEnd;
8126 ++Field) {
8127 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8128 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8129 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8130 false, 0))
8131 ExceptSpec.CalledDecl(MoveAssign);
8132 }
8133 }
8134
8135 return ExceptSpec;
8136}
8137
8138CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8139 // Note: The following rules are largely analoguous to the move
8140 // constructor rules.
8141
8142 ImplicitExceptionSpecification Spec(
8143 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8144
8145 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8146 QualType RetType = Context.getLValueReferenceType(ArgType);
8147 ArgType = Context.getRValueReferenceType(ArgType);
8148
8149 // An implicitly-declared move assignment operator is an inline public
8150 // member of its class.
8151 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8152 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8153 SourceLocation ClassLoc = ClassDecl->getLocation();
8154 DeclarationNameInfo NameInfo(Name, ClassLoc);
8155 CXXMethodDecl *MoveAssignment
8156 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8157 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8158 /*TInfo=*/0, /*isStatic=*/false,
8159 /*StorageClassAsWritten=*/SC_None,
8160 /*isInline=*/true,
8161 /*isConstexpr=*/false,
8162 SourceLocation());
8163 MoveAssignment->setAccess(AS_public);
8164 MoveAssignment->setDefaulted();
8165 MoveAssignment->setImplicit();
8166 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8167
8168 // Add the parameter to the operator.
8169 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8170 ClassLoc, ClassLoc, /*Id=*/0,
8171 ArgType, /*TInfo=*/0,
8172 SC_None,
8173 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008174 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008175
8176 // Note that we have added this copy-assignment operator.
8177 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8178
8179 // C++0x [class.copy]p9:
8180 // If the definition of a class X does not explicitly declare a move
8181 // assignment operator, one will be implicitly declared as defaulted if and
8182 // only if:
8183 // [...]
8184 // - the move assignment operator would not be implicitly defined as
8185 // deleted.
8186 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8187 // Cache this result so that we don't try to generate this over and over
8188 // on every lookup, leaking memory and wasting time.
8189 ClassDecl->setFailedImplicitMoveAssignment();
8190 return 0;
8191 }
8192
8193 if (Scope *S = getScopeForContext(ClassDecl))
8194 PushOnScopeChains(MoveAssignment, S, false);
8195 ClassDecl->addDecl(MoveAssignment);
8196
8197 AddOverriddenMethods(ClassDecl, MoveAssignment);
8198 return MoveAssignment;
8199}
8200
8201void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8202 CXXMethodDecl *MoveAssignOperator) {
8203 assert((MoveAssignOperator->isDefaulted() &&
8204 MoveAssignOperator->isOverloadedOperator() &&
8205 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8206 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8207 "DefineImplicitMoveAssignment called for wrong function");
8208
8209 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8210
8211 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8212 MoveAssignOperator->setInvalidDecl();
8213 return;
8214 }
8215
8216 MoveAssignOperator->setUsed();
8217
8218 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8219 DiagnosticErrorTrap Trap(Diags);
8220
8221 // C++0x [class.copy]p28:
8222 // The implicitly-defined or move assignment operator for a non-union class
8223 // X performs memberwise move assignment of its subobjects. The direct base
8224 // classes of X are assigned first, in the order of their declaration in the
8225 // base-specifier-list, and then the immediate non-static data members of X
8226 // are assigned, in the order in which they were declared in the class
8227 // definition.
8228
8229 // The statements that form the synthesized function body.
8230 ASTOwningVector<Stmt*> Statements(*this);
8231
8232 // The parameter for the "other" object, which we are move from.
8233 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8234 QualType OtherRefType = Other->getType()->
8235 getAs<RValueReferenceType>()->getPointeeType();
8236 assert(OtherRefType.getQualifiers() == 0 &&
8237 "Bad argument type of defaulted move assignment");
8238
8239 // Our location for everything implicitly-generated.
8240 SourceLocation Loc = MoveAssignOperator->getLocation();
8241
8242 // Construct a reference to the "other" object. We'll be using this
8243 // throughout the generated ASTs.
8244 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8245 assert(OtherRef && "Reference to parameter cannot fail!");
8246 // Cast to rvalue.
8247 OtherRef = CastForMoving(*this, OtherRef);
8248
8249 // Construct the "this" pointer. We'll be using this throughout the generated
8250 // ASTs.
8251 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8252 assert(This && "Reference to this cannot fail!");
8253
8254 // Assign base classes.
8255 bool Invalid = false;
8256 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8257 E = ClassDecl->bases_end(); Base != E; ++Base) {
8258 // Form the assignment:
8259 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8260 QualType BaseType = Base->getType().getUnqualifiedType();
8261 if (!BaseType->isRecordType()) {
8262 Invalid = true;
8263 continue;
8264 }
8265
8266 CXXCastPath BasePath;
8267 BasePath.push_back(Base);
8268
8269 // Construct the "from" expression, which is an implicit cast to the
8270 // appropriately-qualified base type.
8271 Expr *From = OtherRef;
8272 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00008273 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00008274
8275 // Dereference "this".
8276 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8277
8278 // Implicitly cast "this" to the appropriately-qualified base type.
8279 To = ImpCastExprToType(To.take(),
8280 Context.getCVRQualifiedType(BaseType,
8281 MoveAssignOperator->getTypeQualifiers()),
8282 CK_UncheckedDerivedToBase,
8283 VK_LValue, &BasePath);
8284
8285 // Build the move.
8286 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8287 To.get(), From,
8288 /*CopyingBaseSubobject=*/true,
8289 /*Copying=*/false);
8290 if (Move.isInvalid()) {
8291 Diag(CurrentLocation, diag::note_member_synthesized_at)
8292 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8293 MoveAssignOperator->setInvalidDecl();
8294 return;
8295 }
8296
8297 // Success! Record the move.
8298 Statements.push_back(Move.takeAs<Expr>());
8299 }
8300
8301 // \brief Reference to the __builtin_memcpy function.
8302 Expr *BuiltinMemCpyRef = 0;
8303 // \brief Reference to the __builtin_objc_memmove_collectable function.
8304 Expr *CollectableMemCpyRef = 0;
8305
8306 // Assign non-static members.
8307 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8308 FieldEnd = ClassDecl->field_end();
8309 Field != FieldEnd; ++Field) {
8310 // Check for members of reference type; we can't move those.
8311 if (Field->getType()->isReferenceType()) {
8312 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8313 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8314 Diag(Field->getLocation(), diag::note_declared_at);
8315 Diag(CurrentLocation, diag::note_member_synthesized_at)
8316 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8317 Invalid = true;
8318 continue;
8319 }
8320
8321 // Check for members of const-qualified, non-class type.
8322 QualType BaseType = Context.getBaseElementType(Field->getType());
8323 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8324 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8325 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8326 Diag(Field->getLocation(), diag::note_declared_at);
8327 Diag(CurrentLocation, diag::note_member_synthesized_at)
8328 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8329 Invalid = true;
8330 continue;
8331 }
8332
8333 // Suppress assigning zero-width bitfields.
8334 if (const Expr *Width = Field->getBitWidth())
8335 if (Width->EvaluateAsInt(Context) == 0)
8336 continue;
8337
8338 QualType FieldType = Field->getType().getNonReferenceType();
8339 if (FieldType->isIncompleteArrayType()) {
8340 assert(ClassDecl->hasFlexibleArrayMember() &&
8341 "Incomplete array type is not valid");
8342 continue;
8343 }
8344
8345 // Build references to the field in the object we're copying from and to.
8346 CXXScopeSpec SS; // Intentionally empty
8347 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8348 LookupMemberName);
8349 MemberLookup.addDecl(*Field);
8350 MemberLookup.resolveKind();
8351 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8352 Loc, /*IsArrow=*/false,
8353 SS, 0, MemberLookup, 0);
8354 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8355 Loc, /*IsArrow=*/true,
8356 SS, 0, MemberLookup, 0);
8357 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8358 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8359
8360 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8361 "Member reference with rvalue base must be rvalue except for reference "
8362 "members, which aren't allowed for move assignment.");
8363
8364 // If the field should be copied with __builtin_memcpy rather than via
8365 // explicit assignments, do so. This optimization only applies for arrays
8366 // of scalars and arrays of class type with trivial move-assignment
8367 // operators.
8368 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8369 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8370 // Compute the size of the memory buffer to be copied.
8371 QualType SizeType = Context.getSizeType();
8372 llvm::APInt Size(Context.getTypeSize(SizeType),
8373 Context.getTypeSizeInChars(BaseType).getQuantity());
8374 for (const ConstantArrayType *Array
8375 = Context.getAsConstantArrayType(FieldType);
8376 Array;
8377 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8378 llvm::APInt ArraySize
8379 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8380 Size *= ArraySize;
8381 }
8382
Douglas Gregor528499b2011-09-01 02:09:07 +00008383 // Take the address of the field references for "from" and "to". We
8384 // directly construct UnaryOperators here because semantic analysis
8385 // does not permit us to take the address of an xvalue.
8386 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8387 Context.getPointerType(From.get()->getType()),
8388 VK_RValue, OK_Ordinary, Loc);
8389 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8390 Context.getPointerType(To.get()->getType()),
8391 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008392
8393 bool NeedsCollectableMemCpy =
8394 (BaseType->isRecordType() &&
8395 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8396
8397 if (NeedsCollectableMemCpy) {
8398 if (!CollectableMemCpyRef) {
8399 // Create a reference to the __builtin_objc_memmove_collectable function.
8400 LookupResult R(*this,
8401 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8402 Loc, LookupOrdinaryName);
8403 LookupName(R, TUScope, true);
8404
8405 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8406 if (!CollectableMemCpy) {
8407 // Something went horribly wrong earlier, and we will have
8408 // complained about it.
8409 Invalid = true;
8410 continue;
8411 }
8412
8413 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8414 CollectableMemCpy->getType(),
8415 VK_LValue, Loc, 0).take();
8416 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8417 }
8418 }
8419 // Create a reference to the __builtin_memcpy builtin function.
8420 else if (!BuiltinMemCpyRef) {
8421 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8422 LookupOrdinaryName);
8423 LookupName(R, TUScope, true);
8424
8425 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8426 if (!BuiltinMemCpy) {
8427 // Something went horribly wrong earlier, and we will have complained
8428 // about it.
8429 Invalid = true;
8430 continue;
8431 }
8432
8433 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8434 BuiltinMemCpy->getType(),
8435 VK_LValue, Loc, 0).take();
8436 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8437 }
8438
8439 ASTOwningVector<Expr*> CallArgs(*this);
8440 CallArgs.push_back(To.takeAs<Expr>());
8441 CallArgs.push_back(From.takeAs<Expr>());
8442 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8443 ExprResult Call = ExprError();
8444 if (NeedsCollectableMemCpy)
8445 Call = ActOnCallExpr(/*Scope=*/0,
8446 CollectableMemCpyRef,
8447 Loc, move_arg(CallArgs),
8448 Loc);
8449 else
8450 Call = ActOnCallExpr(/*Scope=*/0,
8451 BuiltinMemCpyRef,
8452 Loc, move_arg(CallArgs),
8453 Loc);
8454
8455 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8456 Statements.push_back(Call.takeAs<Expr>());
8457 continue;
8458 }
8459
8460 // Build the move of this field.
8461 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8462 To.get(), From.get(),
8463 /*CopyingBaseSubobject=*/false,
8464 /*Copying=*/false);
8465 if (Move.isInvalid()) {
8466 Diag(CurrentLocation, diag::note_member_synthesized_at)
8467 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8468 MoveAssignOperator->setInvalidDecl();
8469 return;
8470 }
8471
8472 // Success! Record the copy.
8473 Statements.push_back(Move.takeAs<Stmt>());
8474 }
8475
8476 if (!Invalid) {
8477 // Add a "return *this;"
8478 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8479
8480 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8481 if (Return.isInvalid())
8482 Invalid = true;
8483 else {
8484 Statements.push_back(Return.takeAs<Stmt>());
8485
8486 if (Trap.hasErrorOccurred()) {
8487 Diag(CurrentLocation, diag::note_member_synthesized_at)
8488 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8489 Invalid = true;
8490 }
8491 }
8492 }
8493
8494 if (Invalid) {
8495 MoveAssignOperator->setInvalidDecl();
8496 return;
8497 }
8498
8499 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8500 /*isStmtExpr=*/false);
8501 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8502 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8503
8504 if (ASTMutationListener *L = getASTMutationListener()) {
8505 L->CompletedImplicitDefinition(MoveAssignOperator);
8506 }
8507}
8508
Alexis Hunt913820d2011-05-13 06:10:58 +00008509std::pair<Sema::ImplicitExceptionSpecification, bool>
8510Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008511 if (ClassDecl->isInvalidDecl())
8512 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8513
Douglas Gregor54be3392010-07-01 17:57:27 +00008514 // C++ [class.copy]p5:
8515 // The implicitly-declared copy constructor for a class X will
8516 // have the form
8517 //
8518 // X::X(const X&)
8519 //
8520 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008521 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008522 bool HasConstCopyConstructor = true;
8523
8524 // -- each direct or virtual base class B of X has a copy
8525 // constructor whose first parameter is of type const B& or
8526 // const volatile B&, and
8527 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8528 BaseEnd = ClassDecl->bases_end();
8529 HasConstCopyConstructor && Base != BaseEnd;
8530 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008531 // Virtual bases are handled below.
8532 if (Base->isVirtual())
8533 continue;
8534
Douglas Gregora6d69502010-07-02 23:41:54 +00008535 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008536 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008537 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8538 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008539 }
8540
8541 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8542 BaseEnd = ClassDecl->vbases_end();
8543 HasConstCopyConstructor && Base != BaseEnd;
8544 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008545 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008546 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008547 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8548 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008549 }
8550
8551 // -- for all the nonstatic data members of X that are of a
8552 // class type M (or array thereof), each such class type
8553 // has a copy constructor whose first parameter is of type
8554 // const M& or const volatile M&.
8555 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8556 FieldEnd = ClassDecl->field_end();
8557 HasConstCopyConstructor && Field != FieldEnd;
8558 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008559 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008560 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008561 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8562 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008563 }
8564 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008565 // Otherwise, the implicitly declared copy constructor will have
8566 // the form
8567 //
8568 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008569
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008570 // C++ [except.spec]p14:
8571 // An implicitly declared special member function (Clause 12) shall have an
8572 // exception-specification. [...]
8573 ImplicitExceptionSpecification ExceptSpec(Context);
8574 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8575 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8576 BaseEnd = ClassDecl->bases_end();
8577 Base != BaseEnd;
8578 ++Base) {
8579 // Virtual bases are handled below.
8580 if (Base->isVirtual())
8581 continue;
8582
Douglas Gregora6d69502010-07-02 23:41:54 +00008583 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008584 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008585 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008586 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008587 ExceptSpec.CalledDecl(CopyConstructor);
8588 }
8589 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8590 BaseEnd = ClassDecl->vbases_end();
8591 Base != BaseEnd;
8592 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008593 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008594 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008595 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008596 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008597 ExceptSpec.CalledDecl(CopyConstructor);
8598 }
8599 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8600 FieldEnd = ClassDecl->field_end();
8601 Field != FieldEnd;
8602 ++Field) {
8603 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008604 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8605 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008606 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008607 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008608 }
8609 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008610
Alexis Hunt913820d2011-05-13 06:10:58 +00008611 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8612}
8613
8614CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8615 CXXRecordDecl *ClassDecl) {
8616 // C++ [class.copy]p4:
8617 // If the class definition does not explicitly declare a copy
8618 // constructor, one is declared implicitly.
8619
8620 ImplicitExceptionSpecification Spec(Context);
8621 bool Const;
8622 llvm::tie(Spec, Const) =
8623 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8624
8625 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8626 QualType ArgType = ClassType;
8627 if (Const)
8628 ArgType = ArgType.withConst();
8629 ArgType = Context.getLValueReferenceType(ArgType);
8630
8631 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8632
Douglas Gregor54be3392010-07-01 17:57:27 +00008633 DeclarationName Name
8634 = Context.DeclarationNames.getCXXConstructorName(
8635 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008636 SourceLocation ClassLoc = ClassDecl->getLocation();
8637 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008638
8639 // An implicitly-declared copy constructor is an inline public
8640 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00008641 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00008642 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00008643 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00008644 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00008645 /*TInfo=*/0,
8646 /*isExplicit=*/false,
8647 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00008648 /*isImplicitlyDeclared=*/true,
8649 // FIXME: apply the rules for definitions here
8650 /*isConstexpr=*/false);
Douglas Gregor54be3392010-07-01 17:57:27 +00008651 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008652 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008653 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8654
Douglas Gregora6d69502010-07-02 23:41:54 +00008655 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008656 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8657
Douglas Gregor54be3392010-07-01 17:57:27 +00008658 // Add the parameter to the constructor.
8659 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008660 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008661 /*IdentifierInfo=*/0,
8662 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008663 SC_None,
8664 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008665 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008666
Douglas Gregor0be31a22010-07-02 17:43:08 +00008667 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008668 PushOnScopeChains(CopyConstructor, S, false);
8669 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008670
Alexis Huntd74c85f2011-06-22 01:05:13 +00008671 // C++0x [class.copy]p7:
8672 // ... If the class definition declares a move constructor or move
8673 // assignment operator, the implicitly declared constructor is defined as
8674 // deleted; ...
8675 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8676 ClassDecl->hasUserDeclaredMoveAssignment() ||
8677 ShouldDeleteCopyConstructor(CopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008678 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008679
8680 return CopyConstructor;
8681}
8682
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008683void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008684 CXXConstructorDecl *CopyConstructor) {
8685 assert((CopyConstructor->isDefaulted() &&
8686 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008687 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008688 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008689
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008690 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008691 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008692
Douglas Gregora57478e2010-05-01 15:04:51 +00008693 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008694 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008695
Alexis Hunt1d792652011-01-08 20:30:50 +00008696 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008697 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008698 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008699 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008700 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008701 } else {
8702 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8703 CopyConstructor->getLocation(),
8704 MultiStmtArg(*this, 0, 0),
8705 /*isStmtExpr=*/false)
8706 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008707 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008708 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008709
8710 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008711 if (ASTMutationListener *L = getASTMutationListener()) {
8712 L->CompletedImplicitDefinition(CopyConstructor);
8713 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008714}
8715
Sebastian Redl22653ba2011-08-30 19:58:05 +00008716Sema::ImplicitExceptionSpecification
8717Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8718 // C++ [except.spec]p14:
8719 // An implicitly declared special member function (Clause 12) shall have an
8720 // exception-specification. [...]
8721 ImplicitExceptionSpecification ExceptSpec(Context);
8722 if (ClassDecl->isInvalidDecl())
8723 return ExceptSpec;
8724
8725 // Direct base-class constructors.
8726 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8727 BEnd = ClassDecl->bases_end();
8728 B != BEnd; ++B) {
8729 if (B->isVirtual()) // Handled below.
8730 continue;
8731
8732 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8733 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8734 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8735 // If this is a deleted function, add it anyway. This might be conformant
8736 // with the standard. This might not. I'm not sure. It might not matter.
8737 if (Constructor)
8738 ExceptSpec.CalledDecl(Constructor);
8739 }
8740 }
8741
8742 // Virtual base-class constructors.
8743 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8744 BEnd = ClassDecl->vbases_end();
8745 B != BEnd; ++B) {
8746 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8747 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8748 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8749 // If this is a deleted function, add it anyway. This might be conformant
8750 // with the standard. This might not. I'm not sure. It might not matter.
8751 if (Constructor)
8752 ExceptSpec.CalledDecl(Constructor);
8753 }
8754 }
8755
8756 // Field constructors.
8757 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8758 FEnd = ClassDecl->field_end();
8759 F != FEnd; ++F) {
8760 if (F->hasInClassInitializer()) {
8761 if (Expr *E = F->getInClassInitializer())
8762 ExceptSpec.CalledExpr(E);
8763 else if (!F->isInvalidDecl())
8764 ExceptSpec.SetDelayed();
8765 } else if (const RecordType *RecordTy
8766 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8767 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8768 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8769 // If this is a deleted function, add it anyway. This might be conformant
8770 // with the standard. This might not. I'm not sure. It might not matter.
8771 // In particular, the problem is that this function never gets called. It
8772 // might just be ill-formed because this function attempts to refer to
8773 // a deleted function here.
8774 if (Constructor)
8775 ExceptSpec.CalledDecl(Constructor);
8776 }
8777 }
8778
8779 return ExceptSpec;
8780}
8781
8782CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8783 CXXRecordDecl *ClassDecl) {
8784 ImplicitExceptionSpecification Spec(
8785 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8786
8787 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8788 QualType ArgType = Context.getRValueReferenceType(ClassType);
8789
8790 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8791
8792 DeclarationName Name
8793 = Context.DeclarationNames.getCXXConstructorName(
8794 Context.getCanonicalType(ClassType));
8795 SourceLocation ClassLoc = ClassDecl->getLocation();
8796 DeclarationNameInfo NameInfo(Name, ClassLoc);
8797
8798 // C++0x [class.copy]p11:
8799 // An implicitly-declared copy/move constructor is an inline public
8800 // member of its class.
8801 CXXConstructorDecl *MoveConstructor
8802 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8803 Context.getFunctionType(Context.VoidTy,
8804 &ArgType, 1, EPI),
8805 /*TInfo=*/0,
8806 /*isExplicit=*/false,
8807 /*isInline=*/true,
8808 /*isImplicitlyDeclared=*/true,
8809 // FIXME: apply the rules for definitions here
8810 /*isConstexpr=*/false);
8811 MoveConstructor->setAccess(AS_public);
8812 MoveConstructor->setDefaulted();
8813 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8814
8815 // Add the parameter to the constructor.
8816 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8817 ClassLoc, ClassLoc,
8818 /*IdentifierInfo=*/0,
8819 ArgType, /*TInfo=*/0,
8820 SC_None,
8821 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008822 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008823
8824 // C++0x [class.copy]p9:
8825 // If the definition of a class X does not explicitly declare a move
8826 // constructor, one will be implicitly declared as defaulted if and only if:
8827 // [...]
8828 // - the move constructor would not be implicitly defined as deleted.
8829 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8830 // Cache this result so that we don't try to generate this over and over
8831 // on every lookup, leaking memory and wasting time.
8832 ClassDecl->setFailedImplicitMoveConstructor();
8833 return 0;
8834 }
8835
8836 // Note that we have declared this constructor.
8837 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8838
8839 if (Scope *S = getScopeForContext(ClassDecl))
8840 PushOnScopeChains(MoveConstructor, S, false);
8841 ClassDecl->addDecl(MoveConstructor);
8842
8843 return MoveConstructor;
8844}
8845
8846void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8847 CXXConstructorDecl *MoveConstructor) {
8848 assert((MoveConstructor->isDefaulted() &&
8849 MoveConstructor->isMoveConstructor() &&
8850 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8851 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8852
8853 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8854 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8855
8856 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8857 DiagnosticErrorTrap Trap(Diags);
8858
8859 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8860 Trap.hasErrorOccurred()) {
8861 Diag(CurrentLocation, diag::note_member_synthesized_at)
8862 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8863 MoveConstructor->setInvalidDecl();
8864 } else {
8865 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8866 MoveConstructor->getLocation(),
8867 MultiStmtArg(*this, 0, 0),
8868 /*isStmtExpr=*/false)
8869 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008870 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008871 }
8872
8873 MoveConstructor->setUsed();
8874
8875 if (ASTMutationListener *L = getASTMutationListener()) {
8876 L->CompletedImplicitDefinition(MoveConstructor);
8877 }
8878}
8879
John McCalldadc5752010-08-24 06:29:42 +00008880ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008881Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00008882 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008883 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008884 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008885 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008886 unsigned ConstructKind,
8887 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00008888 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00008889
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008890 // C++0x [class.copy]p34:
8891 // When certain criteria are met, an implementation is allowed to
8892 // omit the copy/move construction of a class object, even if the
8893 // copy/move constructor and/or destructor for the object have
8894 // side effects. [...]
8895 // - when a temporary class object that has not been bound to a
8896 // reference (12.2) would be copied/moved to a class object
8897 // with the same cv-unqualified type, the copy/move operation
8898 // can be omitted by constructing the temporary object
8899 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00008900 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00008901 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008902 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00008903 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00008904 }
Mike Stump11289f42009-09-09 15:08:12 +00008905
8906 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008907 Elidable, move(ExprArgs), HadMultipleCandidates,
8908 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00008909}
8910
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008911/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8912/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00008913ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008914Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8915 CXXConstructorDecl *Constructor, bool Elidable,
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 Carlsson5995a3e2009-09-07 22:23:31 +00008921 unsigned NumExprs = ExprArgs.size();
8922 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00008923
Nick Lewyckyd4693212011-03-25 01:44:32 +00008924 for (specific_attr_iterator<NonNullAttr>
8925 i = Constructor->specific_attr_begin<NonNullAttr>(),
8926 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8927 const NonNullAttr *NonNull = *i;
8928 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8929 }
8930
Douglas Gregor27381f32009-11-23 12:27:39 +00008931 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00008932 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008933 Constructor, Elidable, Exprs, NumExprs,
8934 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008935 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8936 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008937}
8938
Mike Stump11289f42009-09-09 15:08:12 +00008939bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008940 CXXConstructorDecl *Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008941 MultiExprArg Exprs,
8942 bool HadMultipleCandidates) {
Chandler Carruth01718152010-10-25 08:47:36 +00008943 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00008944 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00008945 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008946 move(Exprs), HadMultipleCandidates, false,
8947 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008948 if (TempResult.isInvalid())
8949 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008950
Anders Carlsson6eb55572009-08-25 05:12:04 +00008951 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00008952 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00008953 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00008954 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00008955 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00008956
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008957 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00008958}
8959
John McCall03c48482010-02-02 09:10:11 +00008960void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00008961 if (VD->isInvalidDecl()) return;
8962
John McCall03c48482010-02-02 09:10:11 +00008963 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00008964 if (ClassDecl->isInvalidDecl()) return;
8965 if (ClassDecl->hasTrivialDestructor()) return;
8966 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00008967
Chandler Carruth86d17d32011-03-27 21:26:48 +00008968 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8969 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8970 CheckDestructorAccess(VD->getLocation(), Destructor,
8971 PDiag(diag::err_access_dtor_var)
8972 << VD->getDeclName()
8973 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00008974
Chandler Carruth86d17d32011-03-27 21:26:48 +00008975 if (!VD->hasGlobalStorage()) return;
8976
8977 // Emit warning for non-trivial dtor in global scope (a real global,
8978 // class-static, function-static).
8979 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8980
8981 // TODO: this should be re-enabled for static locals by !CXAAtExit
8982 if (!VD->isStaticLocal())
8983 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008984}
8985
Mike Stump11289f42009-09-09 15:08:12 +00008986/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008987/// ActOnDeclarator, when a C++ direct initializer is present.
8988/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00008989void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00008990 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008991 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00008992 SourceLocation RParenLoc,
8993 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00008994 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008995
8996 // If there is no declaration, there was an error parsing it. Just ignore
8997 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00008998 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008999 return;
Mike Stump11289f42009-09-09 15:08:12 +00009000
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009001 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9002 if (!VDecl) {
9003 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9004 RealDecl->setInvalidDecl();
9005 return;
9006 }
9007
Richard Smith30482bc2011-02-20 03:19:35 +00009008 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9009 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009010 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
9011 if (Exprs.size() > 1) {
9012 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9013 diag::err_auto_var_init_multiple_expressions)
9014 << VDecl->getDeclName() << VDecl->getType()
9015 << VDecl->getSourceRange();
9016 RealDecl->setInvalidDecl();
9017 return;
9018 }
9019
9020 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00009021 TypeSourceInfo *DeducedType = 0;
9022 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00009023 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
9024 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
9025 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00009026 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00009027 RealDecl->setInvalidDecl();
9028 return;
9029 }
Richard Smith9647d3c2011-03-17 16:11:59 +00009030 VDecl->setTypeSourceInfo(DeducedType);
9031 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00009032
John McCall31168b02011-06-15 23:02:42 +00009033 // In ARC, infer lifetime.
9034 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9035 VDecl->setInvalidDecl();
9036
Richard Smith30482bc2011-02-20 03:19:35 +00009037 // If this is a redeclaration, check that the type we just deduced matches
9038 // the previously declared type.
9039 if (VarDecl *Old = VDecl->getPreviousDeclaration())
9040 MergeVarDeclTypes(VDecl, Old);
9041 }
9042
Douglas Gregor402250f2009-08-26 21:14:46 +00009043 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009044 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009045 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9046 //
9047 // Clients that want to distinguish between the two forms, can check for
9048 // direct initializer using VarDecl::hasCXXDirectInitializer().
9049 // A major benefit is that clients that don't particularly care about which
9050 // exactly form was it (like the CodeGen) can handle both cases without
9051 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009052
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009053 // C++ 8.5p11:
9054 // The form of initialization (using parentheses or '=') is generally
9055 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009056 // class type.
9057
Douglas Gregor50dc2192010-02-11 22:55:30 +00009058 if (!VDecl->getType()->isDependentType() &&
9059 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00009060 diag::err_typecheck_decl_incomplete_type)) {
9061 VDecl->setInvalidDecl();
9062 return;
9063 }
9064
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009065 // The variable can not have an abstract class type.
9066 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9067 diag::err_abstract_type_in_decl,
9068 AbstractVariableType))
9069 VDecl->setInvalidDecl();
9070
Sebastian Redl5ca79842010-02-01 20:16:42 +00009071 const VarDecl *Def;
9072 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009073 Diag(VDecl->getLocation(), diag::err_redefinition)
9074 << VDecl->getDeclName();
9075 Diag(Def->getLocation(), diag::note_previous_definition);
9076 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009077 return;
9078 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00009079
Douglas Gregorf0f83692010-08-24 05:27:49 +00009080 // C++ [class.static.data]p4
9081 // If a static data member is of const integral or const
9082 // enumeration type, its declaration in the class definition can
9083 // specify a constant-initializer which shall be an integral
9084 // constant expression (5.19). In that case, the member can appear
9085 // in integral constant expressions. The member shall still be
9086 // defined in a namespace scope if it is used in the program and the
9087 // namespace scope definition shall not contain an initializer.
9088 //
9089 // We already performed a redefinition check above, but for static
9090 // data members we also need to check whether there was an in-class
9091 // declaration with an initializer.
9092 const VarDecl* PrevInit = 0;
9093 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9094 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9095 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9096 return;
9097 }
9098
Douglas Gregor71f39c92010-12-16 01:31:22 +00009099 bool IsDependent = false;
9100 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9101 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9102 VDecl->setInvalidDecl();
9103 return;
9104 }
9105
9106 if (Exprs.get()[I]->isTypeDependent())
9107 IsDependent = true;
9108 }
9109
Douglas Gregor50dc2192010-02-11 22:55:30 +00009110 // If either the declaration has a dependent type or if any of the
9111 // expressions is type-dependent, we represent the initialization
9112 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00009113 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00009114 // Let clients know that initialization was done with a direct initializer.
9115 VDecl->setCXXDirectInitializer(true);
9116
9117 // Store the initialization expressions as a ParenListExpr.
9118 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00009119 VDecl->setInit(new (Context) ParenListExpr(
9120 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9121 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00009122 return;
9123 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009124
9125 // Capture the variable that is being initialized and the style of
9126 // initialization.
9127 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9128
9129 // FIXME: Poor source location information.
9130 InitializationKind Kind
9131 = InitializationKind::CreateDirect(VDecl->getLocation(),
9132 LParenLoc, RParenLoc);
9133
9134 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00009135 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00009136 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009137 if (Result.isInvalid()) {
9138 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009139 return;
9140 }
John McCallacf0ee52010-10-08 02:01:28 +00009141
Richard Smith2316cd82011-09-29 19:11:37 +00009142 Expr *Init = Result.get();
9143 CheckImplicitConversions(Init, LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009144
Richard Smith2316cd82011-09-29 19:11:37 +00009145 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
9146 !Init->isValueDependent() &&
9147 !Init->isConstantInitializer(Context,
9148 VDecl->getType()->isReferenceType())) {
9149 // FIXME: Improve this diagnostic to explain why the initializer is not
9150 // a constant expression.
9151 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
9152 << VDecl << Init->getSourceRange();
9153 }
9154
9155 Init = MaybeCreateExprWithCleanups(Init);
9156 VDecl->setInit(Init);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009157 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009158
John McCall8b7fd8f12011-01-19 11:48:09 +00009159 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009160}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009161
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009162/// \brief Given a constructor and the set of arguments provided for the
9163/// constructor, convert the arguments and add any required default arguments
9164/// to form a proper call to this constructor.
9165///
9166/// \returns true if an error occurred, false otherwise.
9167bool
9168Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9169 MultiExprArg ArgsPtr,
9170 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00009171 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009172 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9173 unsigned NumArgs = ArgsPtr.size();
9174 Expr **Args = (Expr **)ArgsPtr.get();
9175
9176 const FunctionProtoType *Proto
9177 = Constructor->getType()->getAs<FunctionProtoType>();
9178 assert(Proto && "Constructor without a prototype?");
9179 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009180
9181 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009182 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009183 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009184 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009185 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009186
9187 VariadicCallType CallType =
9188 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009189 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009190 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9191 Proto, 0, Args, NumArgs, AllArgs,
9192 CallType);
9193 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9194 ConvertedArgs.push_back(AllArgs[i]);
9195 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009196}
9197
Anders Carlssone363c8e2009-12-12 00:32:00 +00009198static inline bool
9199CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9200 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009201 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00009202 if (isa<NamespaceDecl>(DC)) {
9203 return SemaRef.Diag(FnDecl->getLocation(),
9204 diag::err_operator_new_delete_declared_in_namespace)
9205 << FnDecl->getDeclName();
9206 }
9207
9208 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00009209 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009210 return SemaRef.Diag(FnDecl->getLocation(),
9211 diag::err_operator_new_delete_declared_static)
9212 << FnDecl->getDeclName();
9213 }
9214
Anders Carlsson60659a82009-12-12 02:43:16 +00009215 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00009216}
9217
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009218static inline bool
9219CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9220 CanQualType ExpectedResultType,
9221 CanQualType ExpectedFirstParamType,
9222 unsigned DependentParamTypeDiag,
9223 unsigned InvalidParamTypeDiag) {
9224 QualType ResultType =
9225 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9226
9227 // Check that the result type is not dependent.
9228 if (ResultType->isDependentType())
9229 return SemaRef.Diag(FnDecl->getLocation(),
9230 diag::err_operator_new_delete_dependent_result_type)
9231 << FnDecl->getDeclName() << ExpectedResultType;
9232
9233 // Check that the result type is what we expect.
9234 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9235 return SemaRef.Diag(FnDecl->getLocation(),
9236 diag::err_operator_new_delete_invalid_result_type)
9237 << FnDecl->getDeclName() << ExpectedResultType;
9238
9239 // A function template must have at least 2 parameters.
9240 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9241 return SemaRef.Diag(FnDecl->getLocation(),
9242 diag::err_operator_new_delete_template_too_few_parameters)
9243 << FnDecl->getDeclName();
9244
9245 // The function decl must have at least 1 parameter.
9246 if (FnDecl->getNumParams() == 0)
9247 return SemaRef.Diag(FnDecl->getLocation(),
9248 diag::err_operator_new_delete_too_few_parameters)
9249 << FnDecl->getDeclName();
9250
9251 // Check the the first parameter type is not dependent.
9252 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9253 if (FirstParamType->isDependentType())
9254 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9255 << FnDecl->getDeclName() << ExpectedFirstParamType;
9256
9257 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00009258 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009259 ExpectedFirstParamType)
9260 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9261 << FnDecl->getDeclName() << ExpectedFirstParamType;
9262
9263 return false;
9264}
9265
Anders Carlsson12308f42009-12-11 23:23:22 +00009266static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009267CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009268 // C++ [basic.stc.dynamic.allocation]p1:
9269 // A program is ill-formed if an allocation function is declared in a
9270 // namespace scope other than global scope or declared static in global
9271 // scope.
9272 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9273 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009274
9275 CanQualType SizeTy =
9276 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9277
9278 // C++ [basic.stc.dynamic.allocation]p1:
9279 // The return type shall be void*. The first parameter shall have type
9280 // std::size_t.
9281 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9282 SizeTy,
9283 diag::err_operator_new_dependent_param_type,
9284 diag::err_operator_new_param_type))
9285 return true;
9286
9287 // C++ [basic.stc.dynamic.allocation]p1:
9288 // The first parameter shall not have an associated default argument.
9289 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00009290 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009291 diag::err_operator_new_default_arg)
9292 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9293
9294 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00009295}
9296
9297static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00009298CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9299 // C++ [basic.stc.dynamic.deallocation]p1:
9300 // A program is ill-formed if deallocation functions are declared in a
9301 // namespace scope other than global scope or declared static in global
9302 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00009303 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9304 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009305
9306 // C++ [basic.stc.dynamic.deallocation]p2:
9307 // Each deallocation function shall return void and its first parameter
9308 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009309 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9310 SemaRef.Context.VoidPtrTy,
9311 diag::err_operator_delete_dependent_param_type,
9312 diag::err_operator_delete_param_type))
9313 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009314
Anders Carlsson12308f42009-12-11 23:23:22 +00009315 return false;
9316}
9317
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009318/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9319/// of this overloaded operator is well-formed. If so, returns false;
9320/// otherwise, emits appropriate diagnostics and returns true.
9321bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00009322 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009323 "Expected an overloaded operator declaration");
9324
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009325 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9326
Mike Stump11289f42009-09-09 15:08:12 +00009327 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009328 // The allocation and deallocation functions, operator new,
9329 // operator new[], operator delete and operator delete[], are
9330 // described completely in 3.7.3. The attributes and restrictions
9331 // found in the rest of this subclause do not apply to them unless
9332 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00009333 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00009334 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00009335
Anders Carlsson22f443f2009-12-12 00:26:23 +00009336 if (Op == OO_New || Op == OO_Array_New)
9337 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009338
9339 // C++ [over.oper]p6:
9340 // An operator function shall either be a non-static member
9341 // function or be a non-member function and have at least one
9342 // parameter whose type is a class, a reference to a class, an
9343 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00009344 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9345 if (MethodDecl->isStatic())
9346 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009347 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009348 } else {
9349 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00009350 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9351 ParamEnd = FnDecl->param_end();
9352 Param != ParamEnd; ++Param) {
9353 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00009354 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9355 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009356 ClassOrEnumParam = true;
9357 break;
9358 }
9359 }
9360
Douglas Gregord69246b2008-11-17 16:14:12 +00009361 if (!ClassOrEnumParam)
9362 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009363 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009364 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009365 }
9366
9367 // C++ [over.oper]p8:
9368 // An operator function cannot have default arguments (8.3.6),
9369 // except where explicitly stated below.
9370 //
Mike Stump11289f42009-09-09 15:08:12 +00009371 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009372 // (C++ [over.call]p1).
9373 if (Op != OO_Call) {
9374 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9375 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009376 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00009377 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00009378 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009379 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009380 }
9381 }
9382
Douglas Gregor6cf08062008-11-10 13:38:07 +00009383 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9384 { false, false, false }
9385#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9386 , { Unary, Binary, MemberOnly }
9387#include "clang/Basic/OperatorKinds.def"
9388 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009389
Douglas Gregor6cf08062008-11-10 13:38:07 +00009390 bool CanBeUnaryOperator = OperatorUses[Op][0];
9391 bool CanBeBinaryOperator = OperatorUses[Op][1];
9392 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009393
9394 // C++ [over.oper]p8:
9395 // [...] Operator functions cannot have more or fewer parameters
9396 // than the number required for the corresponding operator, as
9397 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00009398 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00009399 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009400 if (Op != OO_Call &&
9401 ((NumParams == 1 && !CanBeUnaryOperator) ||
9402 (NumParams == 2 && !CanBeBinaryOperator) ||
9403 (NumParams < 1) || (NumParams > 2))) {
9404 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009405 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00009406 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009407 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00009408 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009409 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009410 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00009411 assert(CanBeBinaryOperator &&
9412 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009413 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009414 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009415
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009416 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009417 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009418 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009419
Douglas Gregord69246b2008-11-17 16:14:12 +00009420 // Overloaded operators other than operator() cannot be variadic.
9421 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009422 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009423 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009424 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009425 }
9426
9427 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009428 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9429 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009430 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009431 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009432 }
9433
9434 // C++ [over.inc]p1:
9435 // The user-defined function called operator++ implements the
9436 // prefix and postfix ++ operator. If this function is a member
9437 // function with no parameters, or a non-member function with one
9438 // parameter of class or enumeration type, it defines the prefix
9439 // increment operator ++ for objects of that type. If the function
9440 // is a member function with one parameter (which shall be of type
9441 // int) or a non-member function with two parameters (the second
9442 // of which shall be of type int), it defines the postfix
9443 // increment operator ++ for objects of that type.
9444 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9445 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9446 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009447 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009448 ParamIsInt = BT->getKind() == BuiltinType::Int;
9449
Chris Lattner2b786902008-11-21 07:50:02 +00009450 if (!ParamIsInt)
9451 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009452 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009453 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009454 }
9455
Douglas Gregord69246b2008-11-17 16:14:12 +00009456 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009457}
Chris Lattner3b024a32008-12-17 07:09:26 +00009458
Alexis Huntc88db062010-01-13 09:01:02 +00009459/// CheckLiteralOperatorDeclaration - Check whether the declaration
9460/// of this literal operator function is well-formed. If so, returns
9461/// false; otherwise, emits appropriate diagnostics and returns true.
9462bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9463 DeclContext *DC = FnDecl->getDeclContext();
9464 Decl::Kind Kind = DC->getDeclKind();
9465 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9466 Kind != Decl::LinkageSpec) {
9467 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9468 << FnDecl->getDeclName();
9469 return true;
9470 }
9471
9472 bool Valid = false;
9473
Alexis Hunt7dd26172010-04-07 23:11:06 +00009474 // template <char...> type operator "" name() is the only valid template
9475 // signature, and the only valid signature with no parameters.
9476 if (FnDecl->param_size() == 0) {
9477 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9478 // Must have only one template parameter
9479 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9480 if (Params->size() == 1) {
9481 NonTypeTemplateParmDecl *PmDecl =
9482 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009483
Alexis Hunt7dd26172010-04-07 23:11:06 +00009484 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009485 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9486 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9487 Valid = true;
9488 }
9489 }
9490 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009491 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009492 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9493
Alexis Huntc88db062010-01-13 09:01:02 +00009494 QualType T = (*Param)->getType();
9495
Alexis Hunt079a6f72010-04-07 22:57:35 +00009496 // unsigned long long int, long double, and any character type are allowed
9497 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009498 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9499 Context.hasSameType(T, Context.LongDoubleTy) ||
9500 Context.hasSameType(T, Context.CharTy) ||
9501 Context.hasSameType(T, Context.WCharTy) ||
9502 Context.hasSameType(T, Context.Char16Ty) ||
9503 Context.hasSameType(T, Context.Char32Ty)) {
9504 if (++Param == FnDecl->param_end())
9505 Valid = true;
9506 goto FinishedParams;
9507 }
9508
Alexis Hunt079a6f72010-04-07 22:57:35 +00009509 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009510 const PointerType *PT = T->getAs<PointerType>();
9511 if (!PT)
9512 goto FinishedParams;
9513 T = PT->getPointeeType();
9514 if (!T.isConstQualified())
9515 goto FinishedParams;
9516 T = T.getUnqualifiedType();
9517
9518 // Move on to the second parameter;
9519 ++Param;
9520
9521 // If there is no second parameter, the first must be a const char *
9522 if (Param == FnDecl->param_end()) {
9523 if (Context.hasSameType(T, Context.CharTy))
9524 Valid = true;
9525 goto FinishedParams;
9526 }
9527
9528 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9529 // are allowed as the first parameter to a two-parameter function
9530 if (!(Context.hasSameType(T, Context.CharTy) ||
9531 Context.hasSameType(T, Context.WCharTy) ||
9532 Context.hasSameType(T, Context.Char16Ty) ||
9533 Context.hasSameType(T, Context.Char32Ty)))
9534 goto FinishedParams;
9535
9536 // The second and final parameter must be an std::size_t
9537 T = (*Param)->getType().getUnqualifiedType();
9538 if (Context.hasSameType(T, Context.getSizeType()) &&
9539 ++Param == FnDecl->param_end())
9540 Valid = true;
9541 }
9542
9543 // FIXME: This diagnostic is absolutely terrible.
9544FinishedParams:
9545 if (!Valid) {
9546 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9547 << FnDecl->getDeclName();
9548 return true;
9549 }
9550
Douglas Gregor86325ad2011-08-30 22:40:35 +00009551 StringRef LiteralName
9552 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9553 if (LiteralName[0] != '_') {
9554 // C++0x [usrlit.suffix]p1:
9555 // Literal suffix identifiers that do not start with an underscore are
9556 // reserved for future standardization.
9557 bool IsHexFloat = true;
9558 if (LiteralName.size() > 1 &&
9559 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9560 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9561 if (!isdigit(LiteralName[I])) {
9562 IsHexFloat = false;
9563 break;
9564 }
9565 }
9566 }
9567
9568 if (IsHexFloat)
9569 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9570 << LiteralName;
9571 else
9572 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9573 }
9574
Alexis Huntc88db062010-01-13 09:01:02 +00009575 return false;
9576}
9577
Douglas Gregor07665a62009-01-05 19:45:36 +00009578/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9579/// linkage specification, including the language and (if present)
9580/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9581/// the location of the language string literal, which is provided
9582/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9583/// the '{' brace. Otherwise, this linkage specification does not
9584/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009585Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9586 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009587 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009588 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009589 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009590 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009591 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009592 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009593 Language = LinkageSpecDecl::lang_cxx;
9594 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009595 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009596 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009597 }
Mike Stump11289f42009-09-09 15:08:12 +00009598
Chris Lattner438e5012008-12-17 07:13:27 +00009599 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009600
Douglas Gregor07665a62009-01-05 19:45:36 +00009601 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009602 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009603 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009604 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009605 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009606}
9607
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009608/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009609/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9610/// valid, it's the position of the closing '}' brace in a linkage
9611/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009612Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009613 Decl *LinkageSpec,
9614 SourceLocation RBraceLoc) {
9615 if (LinkageSpec) {
9616 if (RBraceLoc.isValid()) {
9617 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9618 LSDecl->setRBraceLoc(RBraceLoc);
9619 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009620 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009621 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009622 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009623}
9624
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009625/// \brief Perform semantic analysis for the variable declaration that
9626/// occurs within a C++ catch clause, returning the newly-created
9627/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009628VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009629 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009630 SourceLocation StartLoc,
9631 SourceLocation Loc,
9632 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009633 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009634 QualType ExDeclType = TInfo->getType();
9635
Sebastian Redl54c04d42008-12-22 19:15:10 +00009636 // Arrays and functions decay.
9637 if (ExDeclType->isArrayType())
9638 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9639 else if (ExDeclType->isFunctionType())
9640 ExDeclType = Context.getPointerType(ExDeclType);
9641
9642 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9643 // The exception-declaration shall not denote a pointer or reference to an
9644 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009645 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009646 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009647 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009648 Invalid = true;
9649 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009650
Douglas Gregor104ee002010-03-08 01:47:36 +00009651 // GCC allows catching pointers and references to incomplete types
9652 // as an extension; so do we, but we warn by default.
9653
Sebastian Redl54c04d42008-12-22 19:15:10 +00009654 QualType BaseType = ExDeclType;
9655 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009656 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00009657 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009658 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009659 BaseType = Ptr->getPointeeType();
9660 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00009661 DK = diag::ext_catch_incomplete_ptr;
9662 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00009663 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009664 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009665 BaseType = Ref->getPointeeType();
9666 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00009667 DK = diag::ext_catch_incomplete_ref;
9668 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009669 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009670 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00009671 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9672 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00009673 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009674
Mike Stump11289f42009-09-09 15:08:12 +00009675 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009676 RequireNonAbstractType(Loc, ExDeclType,
9677 diag::err_abstract_type_in_decl,
9678 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009679 Invalid = true;
9680
John McCall2ca705e2010-07-24 00:37:23 +00009681 // Only the non-fragile NeXT runtime currently supports C++ catches
9682 // of ObjC types, and no runtime supports catching ObjC types by value.
9683 if (!Invalid && getLangOptions().ObjC1) {
9684 QualType T = ExDeclType;
9685 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9686 T = RT->getPointeeType();
9687
9688 if (T->isObjCObjectType()) {
9689 Diag(Loc, diag::err_objc_object_catch);
9690 Invalid = true;
9691 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009692 if (!getLangOptions().ObjCNonFragileABI)
9693 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009694 }
9695 }
9696
Abramo Bagnaradff19302011-03-08 08:55:46 +00009697 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9698 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009699 ExDecl->setExceptionVariable(true);
9700
Douglas Gregor750734c2011-07-06 18:14:43 +00009701 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009702 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009703 // C++ [except.handle]p16:
9704 // The object declared in an exception-declaration or, if the
9705 // exception-declaration does not specify a name, a temporary (12.2) is
9706 // copy-initialized (8.5) from the exception object. [...]
9707 // The object is destroyed when the handler exits, after the destruction
9708 // of any automatic objects initialized within the handler.
9709 //
9710 // We just pretend to initialize the object with itself, then make sure
9711 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009712 QualType initType = ExDeclType;
9713
9714 InitializedEntity entity =
9715 InitializedEntity::InitializeVariable(ExDecl);
9716 InitializationKind initKind =
9717 InitializationKind::CreateCopy(Loc, SourceLocation());
9718
9719 Expr *opaqueValue =
9720 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9721 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9722 ExprResult result = sequence.Perform(*this, entity, initKind,
9723 MultiExprArg(&opaqueValue, 1));
9724 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009725 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009726 else {
9727 // If the constructor used was non-trivial, set this as the
9728 // "initializer".
9729 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9730 if (!construct->getConstructor()->isTrivial()) {
9731 Expr *init = MaybeCreateExprWithCleanups(construct);
9732 ExDecl->setInit(init);
9733 }
9734
9735 // And make sure it's destructable.
9736 FinalizeVarWithDestructor(ExDecl, recordType);
9737 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009738 }
9739 }
9740
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009741 if (Invalid)
9742 ExDecl->setInvalidDecl();
9743
9744 return ExDecl;
9745}
9746
9747/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9748/// handler.
John McCall48871652010-08-21 09:40:31 +00009749Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009750 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009751 bool Invalid = D.isInvalidType();
9752
9753 // Check for unexpanded parameter packs.
9754 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9755 UPPC_ExceptionType)) {
9756 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9757 D.getIdentifierLoc());
9758 Invalid = true;
9759 }
9760
Sebastian Redl54c04d42008-12-22 19:15:10 +00009761 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009762 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009763 LookupOrdinaryName,
9764 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009765 // The scope should be freshly made just for us. There is just no way
9766 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009767 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009768 if (PrevDecl->isTemplateParameter()) {
9769 // Maybe we will complain about the shadowed template parameter.
9770 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009771 }
9772 }
9773
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009774 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009775 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9776 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009777 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009778 }
9779
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009780 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009781 D.getSourceRange().getBegin(),
9782 D.getIdentifierLoc(),
9783 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009784 if (Invalid)
9785 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009786
Sebastian Redl54c04d42008-12-22 19:15:10 +00009787 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009788 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009789 PushOnScopeChains(ExDecl, S);
9790 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009791 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009792
Douglas Gregor758a8692009-06-17 21:51:59 +00009793 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009794 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009795}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009796
Abramo Bagnaraea947882011-03-08 16:41:52 +00009797Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009798 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009799 Expr *AssertMessageExpr_,
9800 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009801 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009802
Anders Carlsson54b26982009-03-14 00:33:21 +00009803 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9804 llvm::APSInt Value(32);
9805 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009806 Diag(StaticAssertLoc,
9807 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00009808 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009809 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00009810 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009811
Anders Carlsson54b26982009-03-14 00:33:21 +00009812 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009813 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009814 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009815 }
9816 }
Mike Stump11289f42009-09-09 15:08:12 +00009817
Douglas Gregoref68fee2010-12-15 23:55:21 +00009818 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9819 return 0;
9820
Abramo Bagnaraea947882011-03-08 16:41:52 +00009821 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9822 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009823
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009824 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009825 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009826}
Sebastian Redlf769df52009-03-24 22:27:57 +00009827
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009828/// \brief Perform semantic analysis of the given friend type declaration.
9829///
9830/// \returns A friend declaration that.
9831FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9832 TypeSourceInfo *TSInfo) {
9833 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9834
9835 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009836 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009837
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009838 if (!getLangOptions().CPlusPlus0x) {
9839 // C++03 [class.friend]p2:
9840 // An elaborated-type-specifier shall be used in a friend declaration
9841 // for a class.*
9842 //
9843 // * The class-key of the elaborated-type-specifier is required.
9844 if (!ActiveTemplateInstantiations.empty()) {
9845 // Do not complain about the form of friend template types during
9846 // template instantiation; we will already have complained when the
9847 // template was declared.
9848 } else if (!T->isElaboratedTypeSpecifier()) {
9849 // If we evaluated the type to a record type, suggest putting
9850 // a tag in front.
9851 if (const RecordType *RT = T->getAs<RecordType>()) {
9852 RecordDecl *RD = RT->getDecl();
9853
9854 std::string InsertionText = std::string(" ") + RD->getKindName();
9855
9856 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9857 << (unsigned) RD->getTagKind()
9858 << T
9859 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9860 InsertionText);
9861 } else {
9862 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9863 << T
9864 << SourceRange(FriendLoc, TypeRange.getEnd());
9865 }
9866 } else if (T->getAs<EnumType>()) {
9867 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009868 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009869 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009870 }
9871 }
9872
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009873 // C++0x [class.friend]p3:
9874 // If the type specifier in a friend declaration designates a (possibly
9875 // cv-qualified) class type, that class is declared as a friend; otherwise,
9876 // the friend declaration is ignored.
9877
9878 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9879 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009880
9881 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9882}
9883
John McCallace48cd2010-10-19 01:40:49 +00009884/// Handle a friend tag declaration where the scope specifier was
9885/// templated.
9886Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9887 unsigned TagSpec, SourceLocation TagLoc,
9888 CXXScopeSpec &SS,
9889 IdentifierInfo *Name, SourceLocation NameLoc,
9890 AttributeList *Attr,
9891 MultiTemplateParamsArg TempParamLists) {
9892 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9893
9894 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00009895 bool Invalid = false;
9896
9897 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00009898 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00009899 TempParamLists.get(),
9900 TempParamLists.size(),
9901 /*friend*/ true,
9902 isExplicitSpecialization,
9903 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00009904 if (TemplateParams->size() > 0) {
9905 // This is a declaration of a class template.
9906 if (Invalid)
9907 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009908
Eric Christopher6f228b52011-07-21 05:34:24 +00009909 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9910 SS, Name, NameLoc, Attr,
9911 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +00009912 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +00009913 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009914 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00009915 } else {
9916 // The "template<>" header is extraneous.
9917 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9918 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9919 isExplicitSpecialization = true;
9920 }
9921 }
9922
9923 if (Invalid) return 0;
9924
9925 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9926
9927 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00009928 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00009929 if (TempParamLists.get()[I]->size()) {
9930 isAllExplicitSpecializations = false;
9931 break;
9932 }
9933 }
9934
9935 // FIXME: don't ignore attributes.
9936
9937 // If it's explicit specializations all the way down, just forget
9938 // about the template header and build an appropriate non-templated
9939 // friend. TODO: for source fidelity, remember the headers.
9940 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009941 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00009942 ElaboratedTypeKeyword Keyword
9943 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009944 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009945 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00009946 if (T.isNull())
9947 return 0;
9948
9949 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9950 if (isa<DependentNameType>(T)) {
9951 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9952 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009953 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009954 TL.setNameLoc(NameLoc);
9955 } else {
9956 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9957 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009958 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009959 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9960 }
9961
9962 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9963 TSI, FriendLoc);
9964 Friend->setAccess(AS_public);
9965 CurContext->addDecl(Friend);
9966 return Friend;
9967 }
9968
9969 // Handle the case of a templated-scope friend class. e.g.
9970 // template <class T> class A<T>::B;
9971 // FIXME: we don't support these right now.
9972 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9973 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9974 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9975 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9976 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009977 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00009978 TL.setNameLoc(NameLoc);
9979
9980 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9981 TSI, FriendLoc);
9982 Friend->setAccess(AS_public);
9983 Friend->setUnsupportedFriend(true);
9984 CurContext->addDecl(Friend);
9985 return Friend;
9986}
9987
9988
John McCall11083da2009-09-16 22:47:08 +00009989/// Handle a friend type declaration. This works in tandem with
9990/// ActOnTag.
9991///
9992/// Notes on friend class templates:
9993///
9994/// We generally treat friend class declarations as if they were
9995/// declaring a class. So, for example, the elaborated type specifier
9996/// in a friend declaration is required to obey the restrictions of a
9997/// class-head (i.e. no typedefs in the scope chain), template
9998/// parameters are required to match up with simple template-ids, &c.
9999/// However, unlike when declaring a template specialization, it's
10000/// okay to refer to a template specialization without an empty
10001/// template parameter declaration, e.g.
10002/// friend class A<T>::B<unsigned>;
10003/// We permit this as a special case; if there are any template
10004/// parameters present at all, require proper matching, i.e.
10005/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000010006Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000010007 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010008 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +000010009
10010 assert(DS.isFriendSpecified());
10011 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10012
John McCall11083da2009-09-16 22:47:08 +000010013 // Try to convert the decl specifier to a type. This works for
10014 // friend templates because ActOnTag never produces a ClassTemplateDecl
10015 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000010016 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000010017 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10018 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000010019 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000010020 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010021
Douglas Gregor6c110f32010-12-16 01:14:37 +000010022 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10023 return 0;
10024
John McCall11083da2009-09-16 22:47:08 +000010025 // This is definitely an error in C++98. It's probably meant to
10026 // be forbidden in C++0x, too, but the specification is just
10027 // poorly written.
10028 //
10029 // The problem is with declarations like the following:
10030 // template <T> friend A<T>::foo;
10031 // where deciding whether a class C is a friend or not now hinges
10032 // on whether there exists an instantiation of A that causes
10033 // 'foo' to equal C. There are restrictions on class-heads
10034 // (which we declare (by fiat) elaborated friend declarations to
10035 // be) that makes this tractable.
10036 //
10037 // FIXME: handle "template <> friend class A<T>;", which
10038 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000010039 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000010040 Diag(Loc, diag::err_tagless_friend_type_template)
10041 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010042 return 0;
John McCall11083da2009-09-16 22:47:08 +000010043 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010044
John McCallaa74a0c2009-08-28 07:59:38 +000010045 // C++98 [class.friend]p1: A friend of a class is a function
10046 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000010047 // This is fixed in DR77, which just barely didn't make the C++03
10048 // deadline. It's also a very silly restriction that seriously
10049 // affects inner classes and which nobody else seems to implement;
10050 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000010051 //
10052 // But note that we could warn about it: it's always useless to
10053 // friend one of your own members (it's not, however, worthless to
10054 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000010055
John McCall11083da2009-09-16 22:47:08 +000010056 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010057 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000010058 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010059 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +000010060 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +000010061 TSI,
John McCall11083da2009-09-16 22:47:08 +000010062 DS.getFriendSpecLoc());
10063 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010064 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
10065
10066 if (!D)
John McCall48871652010-08-21 09:40:31 +000010067 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010068
John McCall11083da2009-09-16 22:47:08 +000010069 D->setAccess(AS_public);
10070 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000010071
John McCall48871652010-08-21 09:40:31 +000010072 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000010073}
10074
John McCallde3fd222010-10-12 23:13:28 +000010075Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
10076 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010077 const DeclSpec &DS = D.getDeclSpec();
10078
10079 assert(DS.isFriendSpecified());
10080 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10081
10082 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000010083 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10084 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +000010085
10086 // C++ [class.friend]p1
10087 // A friend of a class is a function or class....
10088 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000010089 // It *doesn't* see through dependent types, which is correct
10090 // according to [temp.arg.type]p3:
10091 // If a declaration acquires a function type through a
10092 // type dependent on a template-parameter and this causes
10093 // a declaration that does not use the syntactic form of a
10094 // function declarator to have a function type, the program
10095 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +000010096 if (!T->isFunctionType()) {
10097 Diag(Loc, diag::err_unexpected_friend);
10098
10099 // It might be worthwhile to try to recover by creating an
10100 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000010101 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010102 }
10103
10104 // C++ [namespace.memdef]p3
10105 // - If a friend declaration in a non-local class first declares a
10106 // class or function, the friend class or function is a member
10107 // of the innermost enclosing namespace.
10108 // - The name of the friend is not found by simple name lookup
10109 // until a matching declaration is provided in that namespace
10110 // scope (either before or after the class declaration granting
10111 // friendship).
10112 // - If a friend function is called, its name may be found by the
10113 // name lookup that considers functions from namespaces and
10114 // classes associated with the types of the function arguments.
10115 // - When looking for a prior declaration of a class or a function
10116 // declared as a friend, scopes outside the innermost enclosing
10117 // namespace scope are not considered.
10118
John McCallde3fd222010-10-12 23:13:28 +000010119 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010120 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10121 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000010122 assert(Name);
10123
Douglas Gregor6c110f32010-12-16 01:14:37 +000010124 // Check for unexpanded parameter packs.
10125 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10126 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10127 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10128 return 0;
10129
John McCall07e91c02009-08-06 02:15:43 +000010130 // The context we found the declaration in, or in which we should
10131 // create the declaration.
10132 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000010133 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010134 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000010135 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000010136
John McCallde3fd222010-10-12 23:13:28 +000010137 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +000010138
John McCallde3fd222010-10-12 23:13:28 +000010139 // There are four cases here.
10140 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +000010141 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +000010142 // there as appropriate.
10143 // Recover from invalid scope qualifiers as if they just weren't there.
10144 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +000010145 // C++0x [namespace.memdef]p3:
10146 // If the name in a friend declaration is neither qualified nor
10147 // a template-id and the declaration is a function or an
10148 // elaborated-type-specifier, the lookup to determine whether
10149 // the entity has been previously declared shall not consider
10150 // any scopes outside the innermost enclosing namespace.
10151 // C++0x [class.friend]p11:
10152 // If a friend declaration appears in a local class and the name
10153 // specified is an unqualified name, a prior declaration is
10154 // looked up without considering scopes that are outside the
10155 // innermost enclosing non-class scope. For a friend function
10156 // declaration, if there is no prior declaration, the program is
10157 // ill-formed.
10158 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +000010159 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000010160
John McCallf7cfb222010-10-13 05:45:15 +000010161 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000010162 DC = CurContext;
10163 while (true) {
10164 // Skip class contexts. If someone can cite chapter and verse
10165 // for this behavior, that would be nice --- it's what GCC and
10166 // EDG do, and it seems like a reasonable intent, but the spec
10167 // really only says that checks for unqualified existing
10168 // declarations should stop at the nearest enclosing namespace,
10169 // not that they should only consider the nearest enclosing
10170 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010171 while (DC->isRecord())
10172 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000010173
John McCall1f82f242009-11-18 22:49:29 +000010174 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +000010175
10176 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +000010177 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +000010178 break;
John McCallf7cfb222010-10-13 05:45:15 +000010179
John McCallf4776592010-10-14 22:22:28 +000010180 if (isTemplateId) {
10181 if (isa<TranslationUnitDecl>(DC)) break;
10182 } else {
10183 if (DC->isFileContext()) break;
10184 }
John McCall07e91c02009-08-06 02:15:43 +000010185 DC = DC->getParent();
10186 }
10187
10188 // C++ [class.friend]p1: A friend of a class is a function or
10189 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +000010190 // C++0x changes this for both friend types and functions.
10191 // Most C++ 98 compilers do seem to give an error here, so
10192 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +000010193 if (!Previous.empty() && DC->Equals(CurContext)
10194 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +000010195 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +000010196
John McCallccbc0322010-10-13 06:22:15 +000010197 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +000010198
John McCallde3fd222010-10-12 23:13:28 +000010199 // - There's a non-dependent scope specifier, in which case we
10200 // compute it and do a previous lookup there for a function
10201 // or function template.
10202 } else if (!SS.getScopeRep()->isDependent()) {
10203 DC = computeDeclContext(SS);
10204 if (!DC) return 0;
10205
10206 if (RequireCompleteDeclContext(SS, DC)) return 0;
10207
10208 LookupQualifiedName(Previous, DC);
10209
10210 // Ignore things found implicitly in the wrong scope.
10211 // TODO: better diagnostics for this case. Suggesting the right
10212 // qualified scope would be nice...
10213 LookupResult::Filter F = Previous.makeFilter();
10214 while (F.hasNext()) {
10215 NamedDecl *D = F.next();
10216 if (!DC->InEnclosingNamespaceSetOf(
10217 D->getDeclContext()->getRedeclContext()))
10218 F.erase();
10219 }
10220 F.done();
10221
10222 if (Previous.empty()) {
10223 D.setInvalidType();
10224 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
10225 return 0;
10226 }
10227
10228 // C++ [class.friend]p1: A friend of a class is a function or
10229 // class that is not a member of the class . . .
10230 if (DC->Equals(CurContext))
10231 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
10232
10233 // - There's a scope specifier that does not match any template
10234 // parameter lists, in which case we use some arbitrary context,
10235 // create a method or method template, and wait for instantiation.
10236 // - There's a scope specifier that does match some template
10237 // parameter lists, which we don't handle right now.
10238 } else {
10239 DC = CurContext;
10240 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000010241 }
10242
John McCallf7cfb222010-10-13 05:45:15 +000010243 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000010244 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000010245 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10246 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10247 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000010248 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000010249 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10250 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000010251 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010252 }
John McCall07e91c02009-08-06 02:15:43 +000010253 }
10254
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010255 bool Redeclaration = false;
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010256 bool AddToScope = true;
John McCallccbc0322010-10-13 06:22:15 +000010257 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +000010258 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +000010259 IsDefinition,
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010260 Redeclaration, AddToScope);
John McCall48871652010-08-21 09:40:31 +000010261 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000010262
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010263 assert(ND->getDeclContext() == DC);
10264 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000010265
John McCall759e32b2009-08-31 22:39:49 +000010266 // Add the function declaration to the appropriate lookup tables,
10267 // adjusting the redeclarations list as necessary. We don't
10268 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000010269 //
John McCall759e32b2009-08-31 22:39:49 +000010270 // Also update the scope-based lookup if the target context's
10271 // lookup context is in lexical scope.
10272 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010273 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010274 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010275 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010276 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010277 }
John McCallaa74a0c2009-08-28 07:59:38 +000010278
10279 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010280 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000010281 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000010282 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000010283 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000010284
John McCallde3fd222010-10-12 23:13:28 +000010285 if (ND->isInvalidDecl())
10286 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +000010287 else {
10288 FunctionDecl *FD;
10289 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10290 FD = FTD->getTemplatedDecl();
10291 else
10292 FD = cast<FunctionDecl>(ND);
10293
10294 // Mark templated-scope function declarations as unsupported.
10295 if (FD->getNumTemplateParameterLists())
10296 FrD->setUnsupportedFriend(true);
10297 }
John McCallde3fd222010-10-12 23:13:28 +000010298
John McCall48871652010-08-21 09:40:31 +000010299 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000010300}
10301
John McCall48871652010-08-21 09:40:31 +000010302void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10303 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000010304
Sebastian Redlf769df52009-03-24 22:27:57 +000010305 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10306 if (!Fn) {
10307 Diag(DelLoc, diag::err_deleted_non_function);
10308 return;
10309 }
10310 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
10311 Diag(DelLoc, diag::err_deleted_decl_not_first);
10312 Diag(Prev->getLocation(), diag::note_previous_declaration);
10313 // If the declaration wasn't the first, we delete the function anyway for
10314 // recovery.
10315 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010316 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000010317}
Sebastian Redl4c018662009-04-27 21:33:24 +000010318
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010319void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10320 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10321
10322 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000010323 if (MD->getParent()->isDependentType()) {
10324 MD->setDefaulted();
10325 MD->setExplicitlyDefaulted();
10326 return;
10327 }
10328
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010329 CXXSpecialMember Member = getSpecialMember(MD);
10330 if (Member == CXXInvalid) {
10331 Diag(DefaultLoc, diag::err_default_special_members);
10332 return;
10333 }
10334
10335 MD->setDefaulted();
10336 MD->setExplicitlyDefaulted();
10337
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010338 // If this definition appears within the record, do the checking when
10339 // the record is complete.
10340 const FunctionDecl *Primary = MD;
10341 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10342 // Find the uninstantiated declaration that actually had the '= default'
10343 // on it.
10344 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10345
10346 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010347 return;
10348
10349 switch (Member) {
10350 case CXXDefaultConstructor: {
10351 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10352 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010353 if (!CD->isInvalidDecl())
10354 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10355 break;
10356 }
10357
10358 case CXXCopyConstructor: {
10359 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10360 CheckExplicitlyDefaultedCopyConstructor(CD);
10361 if (!CD->isInvalidDecl())
10362 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010363 break;
10364 }
Alexis Huntf91729462011-05-12 22:46:25 +000010365
Alexis Huntc9a55732011-05-14 05:23:28 +000010366 case CXXCopyAssignment: {
10367 CheckExplicitlyDefaultedCopyAssignment(MD);
10368 if (!MD->isInvalidDecl())
10369 DefineImplicitCopyAssignment(DefaultLoc, MD);
10370 break;
10371 }
10372
Alexis Huntf91729462011-05-12 22:46:25 +000010373 case CXXDestructor: {
10374 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10375 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010376 if (!DD->isInvalidDecl())
10377 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000010378 break;
10379 }
10380
Sebastian Redl22653ba2011-08-30 19:58:05 +000010381 case CXXMoveConstructor: {
10382 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10383 CheckExplicitlyDefaultedMoveConstructor(CD);
10384 if (!CD->isInvalidDecl())
10385 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000010386 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010387 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000010388
Sebastian Redl22653ba2011-08-30 19:58:05 +000010389 case CXXMoveAssignment: {
10390 CheckExplicitlyDefaultedMoveAssignment(MD);
10391 if (!MD->isInvalidDecl())
10392 DefineImplicitMoveAssignment(DefaultLoc, MD);
10393 break;
10394 }
10395
10396 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000010397 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010398 }
10399 } else {
10400 Diag(DefaultLoc, diag::err_default_special_members);
10401 }
10402}
10403
Sebastian Redl4c018662009-04-27 21:33:24 +000010404static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000010405 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000010406 Stmt *SubStmt = *CI;
10407 if (!SubStmt)
10408 continue;
10409 if (isa<ReturnStmt>(SubStmt))
10410 Self.Diag(SubStmt->getSourceRange().getBegin(),
10411 diag::err_return_in_constructor_handler);
10412 if (!isa<Expr>(SubStmt))
10413 SearchForReturnInStmt(Self, SubStmt);
10414 }
10415}
10416
10417void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10418 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10419 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10420 SearchForReturnInStmt(*this, Handler);
10421 }
10422}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010423
Mike Stump11289f42009-09-09 15:08:12 +000010424bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010425 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010426 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10427 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010428
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010429 if (Context.hasSameType(NewTy, OldTy) ||
10430 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010431 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010432
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010433 // Check if the return types are covariant
10434 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010435
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010436 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010437 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10438 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010439 NewClassTy = NewPT->getPointeeType();
10440 OldClassTy = OldPT->getPointeeType();
10441 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010442 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10443 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10444 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10445 NewClassTy = NewRT->getPointeeType();
10446 OldClassTy = OldRT->getPointeeType();
10447 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010448 }
10449 }
Mike Stump11289f42009-09-09 15:08:12 +000010450
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010451 // The return types aren't either both pointers or references to a class type.
10452 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010453 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010454 diag::err_different_return_type_for_overriding_virtual_function)
10455 << New->getDeclName() << NewTy << OldTy;
10456 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010457
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010458 return true;
10459 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010460
Anders Carlssone60365b2009-12-31 18:34:24 +000010461 // C++ [class.virtual]p6:
10462 // If the return type of D::f differs from the return type of B::f, the
10463 // class type in the return type of D::f shall be complete at the point of
10464 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010465 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10466 if (!RT->isBeingDefined() &&
10467 RequireCompleteType(New->getLocation(), NewClassTy,
10468 PDiag(diag::err_covariant_return_incomplete)
10469 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010470 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010471 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010472
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010473 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010474 // Check if the new class derives from the old class.
10475 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10476 Diag(New->getLocation(),
10477 diag::err_covariant_return_not_derived)
10478 << New->getDeclName() << NewTy << OldTy;
10479 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10480 return true;
10481 }
Mike Stump11289f42009-09-09 15:08:12 +000010482
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010483 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010484 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010485 diag::err_covariant_return_inaccessible_base,
10486 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10487 // FIXME: Should this point to the return type?
10488 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010489 // FIXME: this note won't trigger for delayed access control
10490 // diagnostics, and it's impossible to get an undelayed error
10491 // here from access control during the original parse because
10492 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010493 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10494 return true;
10495 }
10496 }
Mike Stump11289f42009-09-09 15:08:12 +000010497
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010498 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010499 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010500 Diag(New->getLocation(),
10501 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010502 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010503 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10504 return true;
10505 };
Mike Stump11289f42009-09-09 15:08:12 +000010506
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010507
10508 // The new class type must have the same or less qualifiers as the old type.
10509 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10510 Diag(New->getLocation(),
10511 diag::err_covariant_return_type_class_type_more_qualified)
10512 << New->getDeclName() << NewTy << OldTy;
10513 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10514 return true;
10515 };
Mike Stump11289f42009-09-09 15:08:12 +000010516
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010517 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010518}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010519
Douglas Gregor21920e372009-12-01 17:24:26 +000010520/// \brief Mark the given method pure.
10521///
10522/// \param Method the method to be marked pure.
10523///
10524/// \param InitRange the source range that covers the "0" initializer.
10525bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010526 SourceLocation EndLoc = InitRange.getEnd();
10527 if (EndLoc.isValid())
10528 Method->setRangeEnd(EndLoc);
10529
Douglas Gregor21920e372009-12-01 17:24:26 +000010530 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10531 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010532 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010533 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010534
10535 if (!Method->isInvalidDecl())
10536 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10537 << Method->getDeclName() << InitRange;
10538 return true;
10539}
10540
John McCall1f4ee7b2009-12-19 09:28:58 +000010541/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10542/// an initializer for the out-of-line declaration 'Dcl'. The scope
10543/// is a fresh scope pushed for just this purpose.
10544///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010545/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10546/// static data member of class X, names should be looked up in the scope of
10547/// class X.
John McCall48871652010-08-21 09:40:31 +000010548void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010549 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010550 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010551
John McCall1f4ee7b2009-12-19 09:28:58 +000010552 // We should only get called for declarations with scope specifiers, like:
10553 // int foo::bar;
10554 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010555 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010556}
10557
10558/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010559/// initializer for the out-of-line declaration 'D'.
10560void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010561 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010562 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010563
John McCall1f4ee7b2009-12-19 09:28:58 +000010564 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010565 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010566}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010567
10568/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10569/// C++ if/switch/while/for statement.
10570/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010571DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010572 // C++ 6.4p2:
10573 // The declarator shall not specify a function or an array.
10574 // The type-specifier-seq shall not contain typedef and shall not declare a
10575 // new class or enumeration.
10576 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10577 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010578
10579 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010580 if (!Dcl)
10581 return true;
10582
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010583 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10584 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010585 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010586 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010587 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010588
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010589 return Dcl;
10590}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010591
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010592void Sema::LoadExternalVTableUses() {
10593 if (!ExternalSource)
10594 return;
10595
10596 SmallVector<ExternalVTableUse, 4> VTables;
10597 ExternalSource->ReadUsedVTables(VTables);
10598 SmallVector<VTableUse, 4> NewUses;
10599 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10600 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10601 = VTablesUsed.find(VTables[I].Record);
10602 // Even if a definition wasn't required before, it may be required now.
10603 if (Pos != VTablesUsed.end()) {
10604 if (!Pos->second && VTables[I].DefinitionRequired)
10605 Pos->second = true;
10606 continue;
10607 }
10608
10609 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10610 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10611 }
10612
10613 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10614}
10615
Douglas Gregor88d292c2010-05-13 16:44:06 +000010616void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10617 bool DefinitionRequired) {
10618 // Ignore any vtable uses in unevaluated operands or for classes that do
10619 // not have a vtable.
10620 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10621 CurContext->isDependentContext() ||
10622 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010623 return;
10624
Douglas Gregor88d292c2010-05-13 16:44:06 +000010625 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010626 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010627 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10628 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10629 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10630 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010631 // If we already had an entry, check to see if we are promoting this vtable
10632 // to required a definition. If so, we need to reappend to the VTableUses
10633 // list, since we may have already processed the first entry.
10634 if (DefinitionRequired && !Pos.first->second) {
10635 Pos.first->second = true;
10636 } else {
10637 // Otherwise, we can early exit.
10638 return;
10639 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010640 }
10641
10642 // Local classes need to have their virtual members marked
10643 // immediately. For all other classes, we mark their virtual members
10644 // at the end of the translation unit.
10645 if (Class->isLocalClass())
10646 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010647 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010648 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010649}
10650
Douglas Gregor88d292c2010-05-13 16:44:06 +000010651bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010652 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010653 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010654 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010655
Douglas Gregor88d292c2010-05-13 16:44:06 +000010656 // Note: The VTableUses vector could grow as a result of marking
10657 // the members of a class as "used", so we check the size each
10658 // time through the loop and prefer indices (with are stable) to
10659 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010660 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010661 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010662 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010663 if (!Class)
10664 continue;
10665
10666 SourceLocation Loc = VTableUses[I].second;
10667
10668 // If this class has a key function, but that key function is
10669 // defined in another translation unit, we don't need to emit the
10670 // vtable even though we're using it.
10671 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010672 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010673 switch (KeyFunction->getTemplateSpecializationKind()) {
10674 case TSK_Undeclared:
10675 case TSK_ExplicitSpecialization:
10676 case TSK_ExplicitInstantiationDeclaration:
10677 // The key function is in another translation unit.
10678 continue;
10679
10680 case TSK_ExplicitInstantiationDefinition:
10681 case TSK_ImplicitInstantiation:
10682 // We will be instantiating the key function.
10683 break;
10684 }
10685 } else if (!KeyFunction) {
10686 // If we have a class with no key function that is the subject
10687 // of an explicit instantiation declaration, suppress the
10688 // vtable; it will live with the explicit instantiation
10689 // definition.
10690 bool IsExplicitInstantiationDeclaration
10691 = Class->getTemplateSpecializationKind()
10692 == TSK_ExplicitInstantiationDeclaration;
10693 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10694 REnd = Class->redecls_end();
10695 R != REnd; ++R) {
10696 TemplateSpecializationKind TSK
10697 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10698 if (TSK == TSK_ExplicitInstantiationDeclaration)
10699 IsExplicitInstantiationDeclaration = true;
10700 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10701 IsExplicitInstantiationDeclaration = false;
10702 break;
10703 }
10704 }
10705
10706 if (IsExplicitInstantiationDeclaration)
10707 continue;
10708 }
10709
10710 // Mark all of the virtual members of this class as referenced, so
10711 // that we can build a vtable. Then, tell the AST consumer that a
10712 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010713 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010714 MarkVirtualMembersReferenced(Loc, Class);
10715 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10716 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10717
10718 // Optionally warn if we're emitting a weak vtable.
10719 if (Class->getLinkage() == ExternalLinkage &&
10720 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010721 const FunctionDecl *KeyFunctionDef = 0;
10722 if (!KeyFunction ||
10723 (KeyFunction->hasBody(KeyFunctionDef) &&
10724 KeyFunctionDef->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +000010725 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10726 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010727 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010728 VTableUses.clear();
10729
Douglas Gregor97509692011-04-22 22:25:37 +000010730 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010731}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010732
Rafael Espindola5b334082010-03-26 00:36:59 +000010733void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10734 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010735 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10736 e = RD->method_end(); i != e; ++i) {
10737 CXXMethodDecl *MD = *i;
10738
10739 // C++ [basic.def.odr]p2:
10740 // [...] A virtual member function is used if it is not pure. [...]
10741 if (MD->isVirtual() && !MD->isPure())
10742 MarkDeclarationReferenced(Loc, MD);
10743 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010744
10745 // Only classes that have virtual bases need a VTT.
10746 if (RD->getNumVBases() == 0)
10747 return;
10748
10749 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10750 e = RD->bases_end(); i != e; ++i) {
10751 const CXXRecordDecl *Base =
10752 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010753 if (Base->getNumVBases() == 0)
10754 continue;
10755 MarkVirtualMembersReferenced(Loc, Base);
10756 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010757}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010758
10759/// SetIvarInitializers - This routine builds initialization ASTs for the
10760/// Objective-C implementation whose ivars need be initialized.
10761void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10762 if (!getLangOptions().CPlusPlus)
10763 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010764 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010765 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010766 CollectIvarsToConstructOrDestruct(OID, ivars);
10767 if (ivars.empty())
10768 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010769 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010770 for (unsigned i = 0; i < ivars.size(); i++) {
10771 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010772 if (Field->isInvalidDecl())
10773 continue;
10774
Alexis Hunt1d792652011-01-08 20:30:50 +000010775 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010776 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10777 InitializationKind InitKind =
10778 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10779
10780 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010781 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010782 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010783 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010784 // Note, MemberInit could actually come back empty if no initialization
10785 // is required (e.g., because it would call a trivial default constructor)
10786 if (!MemberInit.get() || MemberInit.isInvalid())
10787 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010788
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010789 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010790 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10791 SourceLocation(),
10792 MemberInit.takeAs<Expr>(),
10793 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010794 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010795
10796 // Be sure that the destructor is accessible and is marked as referenced.
10797 if (const RecordType *RecordTy
10798 = Context.getBaseElementType(Field->getType())
10799 ->getAs<RecordType>()) {
10800 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010801 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +000010802 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10803 CheckDestructorAccess(Field->getLocation(), Destructor,
10804 PDiag(diag::err_access_dtor_ivar)
10805 << Context.getBaseElementType(Field->getType()));
10806 }
10807 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010808 }
10809 ObjCImplementation->setIvarInitializers(Context,
10810 AllToInit.data(), AllToInit.size());
10811 }
10812}
Alexis Hunt6118d662011-05-04 05:57:24 +000010813
Alexis Hunt27a761d2011-05-04 23:29:54 +000010814static
10815void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10816 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10817 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10818 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10819 Sema &S) {
10820 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10821 CE = Current.end();
10822 if (Ctor->isInvalidDecl())
10823 return;
10824
10825 const FunctionDecl *FNTarget = 0;
10826 CXXConstructorDecl *Target;
10827
10828 // We ignore the result here since if we don't have a body, Target will be
10829 // null below.
10830 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10831 Target
10832= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10833
10834 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10835 // Avoid dereferencing a null pointer here.
10836 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10837
10838 if (!Current.insert(Canonical))
10839 return;
10840
10841 // We know that beyond here, we aren't chaining into a cycle.
10842 if (!Target || !Target->isDelegatingConstructor() ||
10843 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10844 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10845 Valid.insert(*CI);
10846 Current.clear();
10847 // We've hit a cycle.
10848 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10849 Current.count(TCanonical)) {
10850 // If we haven't diagnosed this cycle yet, do so now.
10851 if (!Invalid.count(TCanonical)) {
10852 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000010853 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000010854 << Ctor;
10855
10856 // Don't add a note for a function delegating directo to itself.
10857 if (TCanonical != Canonical)
10858 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10859
10860 CXXConstructorDecl *C = Target;
10861 while (C->getCanonicalDecl() != Canonical) {
10862 (void)C->getTargetConstructor()->hasBody(FNTarget);
10863 assert(FNTarget && "Ctor cycle through bodiless function");
10864
10865 C
10866 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10867 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10868 }
10869 }
10870
10871 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10872 Invalid.insert(*CI);
10873 Current.clear();
10874 } else {
10875 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10876 }
10877}
10878
10879
Alexis Hunt6118d662011-05-04 05:57:24 +000010880void Sema::CheckDelegatingCtorCycles() {
10881 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10882
Alexis Hunt27a761d2011-05-04 23:29:54 +000010883 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10884 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000010885
Douglas Gregorbae31202011-07-27 21:57:17 +000010886 for (DelegatingCtorDeclsType::iterator
10887 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000010888 E = DelegatingCtorDecls.end();
10889 I != E; ++I) {
10890 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000010891 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000010892
10893 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10894 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000010895}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010896
10897/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10898Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10899 // Implicitly declared functions (e.g. copy constructors) are
10900 // __host__ __device__
10901 if (D->isImplicit())
10902 return CFT_HostDevice;
10903
10904 if (D->hasAttr<CUDAGlobalAttr>())
10905 return CFT_Global;
10906
10907 if (D->hasAttr<CUDADeviceAttr>()) {
10908 if (D->hasAttr<CUDAHostAttr>())
10909 return CFT_HostDevice;
10910 else
10911 return CFT_Device;
10912 }
10913
10914 return CFT_Host;
10915}
10916
10917bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10918 CUDAFunctionTarget CalleeTarget) {
10919 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10920 // Callable from the device only."
10921 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10922 return true;
10923
10924 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10925 // Callable from the host only."
10926 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10927 // Callable from the host only."
10928 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10929 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10930 return true;
10931
10932 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10933 return true;
10934
10935 return false;
10936}