blob: 6a7af457bb50989437d80ecfa9a847c0ee2bce25 [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"
Benjamin Kramer49038022012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000036#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000037#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000038#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000039
40using namespace clang;
41
Chris Lattner58258242008-04-10 02:22:51 +000042//===----------------------------------------------------------------------===//
43// CheckDefaultArgumentVisitor
44//===----------------------------------------------------------------------===//
45
Chris Lattnerb0d38442008-04-12 23:52:44 +000046namespace {
47 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
48 /// the default argument of a parameter to determine whether it
49 /// contains any ill-formed subexpressions. For example, this will
50 /// diagnose the use of local variables or parameters within the
51 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000052 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000053 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 Expr *DefaultArg;
55 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000056
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 public:
Mike Stump11289f42009-09-09 15:08:12 +000058 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000060
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 bool VisitExpr(Expr *Node);
62 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000063 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 };
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 /// VisitExpr - Visit all of the children of this expression.
67 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
68 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000069 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000070 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000072 }
73
Chris Lattnerb0d38442008-04-12 23:52:44 +000074 /// VisitDeclRefExpr - Visit a reference to a declaration, to
75 /// determine whether this declaration can be used in the default
76 /// argument expression.
77 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000079 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
80 // C++ [dcl.fct.default]p9
81 // Default arguments are evaluated each time the function is
82 // called. The order of evaluation of function arguments is
83 // unspecified. Consequently, parameters of a function shall not
84 // be used in default argument expressions, even if they are not
85 // evaluated. Parameters of a function declared before a default
86 // argument expression are in scope and can hide namespace and
87 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000088 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000089 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000090 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000091 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000092 // C++ [dcl.fct.default]p7
93 // Local variables shall not be used in default argument
94 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000095 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000096 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000097 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000098 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 }
Chris Lattner58258242008-04-10 02:22:51 +0000100
Douglas Gregor8e12c382008-11-04 13:41:56 +0000101 return false;
102 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000103
Douglas Gregor97a9c812008-11-04 14:32:21 +0000104 /// VisitCXXThisExpr - Visit a C++ "this" expression.
105 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
106 // C++ [dcl.fct.default]p8:
107 // The keyword this shall not be used in a default argument of a
108 // member function.
109 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000110 diag::err_param_default_argument_references_this)
111 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000112 }
Chris Lattner58258242008-04-10 02:22:51 +0000113}
114
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000115void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000116 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith938f40b2011-06-11 17:19:42 +0000117 // If we have an MSAny or unknown spec already, don't bother.
118 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000119 return;
120
121 const FunctionProtoType *Proto
122 = Method->getType()->getAs<FunctionProtoType>();
123
124 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
125
126 // If this function can throw any exceptions, make a note of that.
Richard Smith938f40b2011-06-11 17:19:42 +0000127 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000128 ClearExceptions();
129 ComputedEST = EST;
130 return;
131 }
132
Richard Smith938f40b2011-06-11 17:19:42 +0000133 // FIXME: If the call to this decl is using any of its default arguments, we
134 // need to search them for potentially-throwing calls.
135
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000136 // If this function has a basic noexcept, it doesn't affect the outcome.
137 if (EST == EST_BasicNoexcept)
138 return;
139
140 // If we have a throw-all spec at this point, ignore the function.
141 if (ComputedEST == EST_None)
142 return;
143
144 // If we're still at noexcept(true) and there's a nothrow() callee,
145 // change to that specification.
146 if (EST == EST_DynamicNone) {
147 if (ComputedEST == EST_BasicNoexcept)
148 ComputedEST = EST_DynamicNone;
149 return;
150 }
151
152 // Check out noexcept specs.
153 if (EST == EST_ComputedNoexcept) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000154 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 assert(NR != FunctionProtoType::NR_NoNoexcept &&
156 "Must have noexcept result for EST_ComputedNoexcept.");
157 assert(NR != FunctionProtoType::NR_Dependent &&
158 "Should not generate implicit declarations for dependent cases, "
159 "and don't know how to handle them anyway.");
160
161 // noexcept(false) -> no spec on the new function
162 if (NR == FunctionProtoType::NR_Throw) {
163 ClearExceptions();
164 ComputedEST = EST_None;
165 }
166 // noexcept(true) won't change anything either.
167 return;
168 }
169
170 assert(EST == EST_Dynamic && "EST case not considered earlier.");
171 assert(ComputedEST != EST_None &&
172 "Shouldn't collect exceptions when throw-all is guaranteed.");
173 ComputedEST = EST_Dynamic;
174 // Record the exceptions in this function's exception specification.
175 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
176 EEnd = Proto->exception_end();
177 E != EEnd; ++E)
Alexis Hunt913820d2011-05-13 06:10:58 +0000178 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000179 Exceptions.push_back(*E);
180}
181
Richard Smith938f40b2011-06-11 17:19:42 +0000182void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
183 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
184 return;
185
186 // FIXME:
187 //
188 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000189 // [An] implicit exception-specification specifies the type-id T if and
190 // only if T is allowed by the exception-specification of a function directly
191 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000192 // function it directly invokes allows all exceptions, and f shall allow no
193 // exceptions if every function it directly invokes allows no exceptions.
194 //
195 // Note in particular that if an implicit exception-specification is generated
196 // for a function containing a throw-expression, that specification can still
197 // be noexcept(true).
198 //
199 // Note also that 'directly invoked' is not defined in the standard, and there
200 // is no indication that we should only consider potentially-evaluated calls.
201 //
202 // Ultimately we should implement the intent of the standard: the exception
203 // specification should be the set of exceptions which can be thrown by the
204 // implicit definition. For now, we assume that any non-nothrow expression can
205 // throw any exception.
206
207 if (E->CanThrow(*Context))
208 ComputedEST = EST_None;
209}
210
Anders Carlssonc80a1272009-08-25 02:29:20 +0000211bool
John McCallb268a282010-08-23 23:25:46 +0000212Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000213 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000214 if (RequireCompleteType(Param->getLocation(), Param->getType(),
215 diag::err_typecheck_decl_incomplete_type)) {
216 Param->setInvalidDecl();
217 return true;
218 }
219
Anders Carlssonc80a1272009-08-25 02:29:20 +0000220 // C++ [dcl.fct.default]p5
221 // A default argument expression is implicitly converted (clause
222 // 4) to the parameter type. The default argument expression has
223 // the same semantic constraints as the initializer expression in
224 // a declaration of a variable of the parameter type, using the
225 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000226 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
227 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000228 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
229 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000230 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000231 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000232 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000233 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000234 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000235 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000236
John McCallacf0ee52010-10-08 02:01:28 +0000237 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000238 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000239
Anders Carlssonc80a1272009-08-25 02:29:20 +0000240 // Okay: add the default argument to the parameter
241 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000242
Douglas Gregor758cb672010-10-12 18:23:32 +0000243 // We have already instantiated this parameter; provide each of the
244 // instantiations with the uninstantiated default argument.
245 UnparsedDefaultArgInstantiationsMap::iterator InstPos
246 = UnparsedDefaultArgInstantiations.find(Param);
247 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
248 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
249 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
250
251 // We're done tracking this parameter's instantiations.
252 UnparsedDefaultArgInstantiations.erase(InstPos);
253 }
254
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000255 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000256}
257
Chris Lattner58258242008-04-10 02:22:51 +0000258/// ActOnParamDefaultArgument - Check whether the default argument
259/// provided for a function parameter is well-formed. If so, attach it
260/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000261void
John McCall48871652010-08-21 09:40:31 +0000262Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000263 Expr *DefaultArg) {
264 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000265 return;
Mike Stump11289f42009-09-09 15:08:12 +0000266
John McCall48871652010-08-21 09:40:31 +0000267 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000268 UnparsedDefaultArgLocs.erase(Param);
269
Chris Lattner199abbc2008-04-08 05:04:30 +0000270 // Default arguments are only permitted in C++
271 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000272 Diag(EqualLoc, diag::err_param_default_argument)
273 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000274 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000275 return;
276 }
277
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000278 // Check for unexpanded parameter packs.
279 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
280 Param->setInvalidDecl();
281 return;
282 }
283
Anders Carlssonf1c26952009-08-25 01:02:06 +0000284 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000285 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
286 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000287 Param->setInvalidDecl();
288 return;
289 }
Mike Stump11289f42009-09-09 15:08:12 +0000290
John McCallb268a282010-08-23 23:25:46 +0000291 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000292}
293
Douglas Gregor58354032008-12-24 00:01:03 +0000294/// ActOnParamUnparsedDefaultArgument - We've seen a default
295/// argument for a function parameter, but we can't parse it yet
296/// because we're inside a class definition. Note that this default
297/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000298void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000299 SourceLocation EqualLoc,
300 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 if (!param)
302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000305 if (Param)
306 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000307
Anders Carlsson84613c42009-06-12 16:51:40 +0000308 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000309}
310
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
312/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000313void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump11289f42009-09-09 15:08:12 +0000316
John McCall48871652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Anders Carlsson84613c42009-06-12 16:51:40 +0000319 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000320
Anders Carlsson84613c42009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000322}
323
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000324/// CheckExtraCXXDefaultArguments - Check for any extra default
325/// arguments in the declarator, which is not a function declaration
326/// or definition and therefore is not permitted to have default
327/// arguments. This routine should be invoked for every declarator
328/// that is not a function declaration or definition.
329void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
330 // C++ [dcl.fct.default]p3
331 // A default argument expression shall be specified only in the
332 // parameter-declaration-clause of a function declaration or in a
333 // template-parameter (14.1). It shall not be specified for a
334 // parameter pack. If it is specified in a
335 // parameter-declaration-clause, it shall not occur within a
336 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000337 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000338 DeclaratorChunk &chunk = D.getTypeObject(i);
339 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000340 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
341 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000342 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000343 if (Param->hasUnparsedDefaultArg()) {
344 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000345 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
346 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
347 delete Toks;
348 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000349 } else if (Param->getDefaultArg()) {
350 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
351 << Param->getDefaultArg()->getSourceRange();
352 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000353 }
354 }
355 }
356 }
357}
358
Chris Lattner199abbc2008-04-08 05:04:30 +0000359// MergeCXXFunctionDecl - Merge two declarations of the same C++
360// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000361// type. Subroutine of MergeFunctionDecl. Returns true if there was an
362// error, false otherwise.
363bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
364 bool Invalid = false;
365
Chris Lattner199abbc2008-04-08 05:04:30 +0000366 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000367 // For non-template functions, default arguments can be added in
368 // later declarations of a function in the same
369 // scope. Declarations in different scopes have completely
370 // distinct sets of default arguments. That is, declarations in
371 // inner scopes do not acquire default arguments from
372 // declarations in outer scopes, and vice versa. In a given
373 // function declaration, all parameters subsequent to a
374 // parameter with a default argument shall have default
375 // arguments supplied in this or previous declarations. A
376 // default argument shall not be redefined by a later
377 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000378 //
379 // C++ [dcl.fct.default]p6:
380 // Except for member functions of class templates, the default arguments
381 // in a member function definition that appears outside of the class
382 // definition are added to the set of default arguments provided by the
383 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000384 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
385 ParmVarDecl *OldParam = Old->getParamDecl(p);
386 ParmVarDecl *NewParam = New->getParamDecl(p);
387
Douglas Gregorc732aba2009-09-11 18:44:32 +0000388 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000389
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000390 unsigned DiagDefaultParamID =
391 diag::err_param_default_argument_redefinition;
392
393 // MSVC accepts that default parameters be redefined for member functions
394 // of template class. The new default parameter's value is ignored.
395 Invalid = true;
Francois Pichet0706d202011-09-17 17:15:52 +0000396 if (getLangOptions().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000397 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
398 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000399 // Merge the old default argument into the new parameter.
400 NewParam->setHasInheritedDefaultArg();
401 if (OldParam->hasUninstantiatedDefaultArg())
402 NewParam->setUninstantiatedDefaultArg(
403 OldParam->getUninstantiatedDefaultArg());
404 else
405 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000406 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000407 Invalid = false;
408 }
409 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000410
Francois Pichet8cb243a2011-04-10 04:58:30 +0000411 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
412 // hint here. Alternatively, we could walk the type-source information
413 // for NewParam to find the last source location in the type... but it
414 // isn't worth the effort right now. This is the kind of test case that
415 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000416 // int f(int);
417 // void g(int (*fp)(int) = f);
418 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000419 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000420 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000421
422 // Look for the function declaration where the default argument was
423 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000424 for (FunctionDecl *Older = Old->getPreviousDecl();
425 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000426 if (!Older->getParamDecl(p)->hasDefaultArg())
427 break;
428
429 OldParam = Older->getParamDecl(p);
430 }
431
432 Diag(OldParam->getLocation(), diag::note_previous_definition)
433 << OldParam->getDefaultArgRange();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000434 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000435 // Merge the old default argument into the new parameter.
436 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000437 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000438 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000439 if (OldParam->hasUninstantiatedDefaultArg())
440 NewParam->setUninstantiatedDefaultArg(
441 OldParam->getUninstantiatedDefaultArg());
442 else
John McCalle61b02b2010-05-04 01:53:42 +0000443 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000444 } else if (NewParam->hasDefaultArg()) {
445 if (New->getDescribedFunctionTemplate()) {
446 // Paragraph 4, quoted above, only applies to non-template functions.
447 Diag(NewParam->getLocation(),
448 diag::err_param_default_argument_template_redecl)
449 << NewParam->getDefaultArgRange();
450 Diag(Old->getLocation(), diag::note_template_prev_declaration)
451 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000452 } else if (New->getTemplateSpecializationKind()
453 != TSK_ImplicitInstantiation &&
454 New->getTemplateSpecializationKind() != TSK_Undeclared) {
455 // C++ [temp.expr.spec]p21:
456 // Default function arguments shall not be specified in a declaration
457 // or a definition for one of the following explicit specializations:
458 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000459 // - the explicit specialization of a member function template;
460 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000461 // template where the class template specialization to which the
462 // member function specialization belongs is implicitly
463 // instantiated.
464 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
465 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
466 << New->getDeclName()
467 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000468 } else if (New->getDeclContext()->isDependentContext()) {
469 // C++ [dcl.fct.default]p6 (DR217):
470 // Default arguments for a member function of a class template shall
471 // be specified on the initial declaration of the member function
472 // within the class template.
473 //
474 // Reading the tea leaves a bit in DR217 and its reference to DR205
475 // leads me to the conclusion that one cannot add default function
476 // arguments for an out-of-line definition of a member function of a
477 // dependent type.
478 int WhichKind = 2;
479 if (CXXRecordDecl *Record
480 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
481 if (Record->getDescribedClassTemplate())
482 WhichKind = 0;
483 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
484 WhichKind = 1;
485 else
486 WhichKind = 2;
487 }
488
489 Diag(NewParam->getLocation(),
490 diag::err_param_default_argument_member_template_redecl)
491 << WhichKind
492 << NewParam->getDefaultArgRange();
Alexis Huntd051b872011-05-26 01:26:05 +0000493 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
494 CXXSpecialMember NewSM = getSpecialMember(Ctor),
495 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
496 if (NewSM != OldSM) {
497 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
498 << NewParam->getDefaultArgRange() << NewSM;
499 Diag(Old->getLocation(), diag::note_previous_declaration_special)
500 << OldSM;
501 }
Douglas Gregorc732aba2009-09-11 18:44:32 +0000502 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000503 }
504 }
505
Richard Smitheb3c10c2011-10-01 02:31:28 +0000506 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
507 // template has a constexpr specifier then all its declarations shall
508 // contain the constexpr specifier. [Note: An explicit specialization can
509 // differ from the template declaration with respect to the constexpr
510 // specifier. -- end note]
511 //
512 // FIXME: Don't reject changes in constexpr in explicit specializations.
513 if (New->isConstexpr() != Old->isConstexpr()) {
514 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
515 << New << New->isConstexpr();
516 Diag(Old->getLocation(), diag::note_previous_declaration);
517 Invalid = true;
518 }
519
Douglas Gregorf40863c2010-02-12 07:32:17 +0000520 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000521 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000522
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000523 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000524}
525
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000526/// \brief Merge the exception specifications of two variable declarations.
527///
528/// This is called when there's a redeclaration of a VarDecl. The function
529/// checks if the redeclaration might have an exception specification and
530/// validates compatibility and merges the specs if necessary.
531void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
532 // Shortcut if exceptions are disabled.
533 if (!getLangOptions().CXXExceptions)
534 return;
535
536 assert(Context.hasSameType(New->getType(), Old->getType()) &&
537 "Should only be called if types are otherwise the same.");
538
539 QualType NewType = New->getType();
540 QualType OldType = Old->getType();
541
542 // We're only interested in pointers and references to functions, as well
543 // as pointers to member functions.
544 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
545 NewType = R->getPointeeType();
546 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
547 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
548 NewType = P->getPointeeType();
549 OldType = OldType->getAs<PointerType>()->getPointeeType();
550 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
551 NewType = M->getPointeeType();
552 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
553 }
554
555 if (!NewType->isFunctionProtoType())
556 return;
557
558 // There's lots of special cases for functions. For function pointers, system
559 // libraries are hopefully not as broken so that we don't need these
560 // workarounds.
561 if (CheckEquivalentExceptionSpec(
562 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
563 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
564 New->setInvalidDecl();
565 }
566}
567
Chris Lattner199abbc2008-04-08 05:04:30 +0000568/// CheckCXXDefaultArguments - Verify that the default arguments for a
569/// function declaration are well-formed according to C++
570/// [dcl.fct.default].
571void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
572 unsigned NumParams = FD->getNumParams();
573 unsigned p;
574
575 // Find first parameter with a default argument
576 for (p = 0; p < NumParams; ++p) {
577 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000578 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000579 break;
580 }
581
582 // C++ [dcl.fct.default]p4:
583 // In a given function declaration, all parameters
584 // subsequent to a parameter with a default argument shall
585 // have default arguments supplied in this or previous
586 // declarations. A default argument shall not be redefined
587 // by a later declaration (not even to the same value).
588 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000589 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000590 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000591 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000592 if (Param->isInvalidDecl())
593 /* We already complained about this parameter. */;
594 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000595 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000596 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000597 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000598 else
Mike Stump11289f42009-09-09 15:08:12 +0000599 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000600 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000601
Chris Lattner199abbc2008-04-08 05:04:30 +0000602 LastMissingDefaultArg = p;
603 }
604 }
605
606 if (LastMissingDefaultArg > 0) {
607 // Some default arguments were missing. Clear out all of the
608 // default arguments up to (and including) the last missing
609 // default argument, so that we leave the function parameters
610 // in a semantically valid state.
611 for (p = 0; p <= LastMissingDefaultArg; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000613 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000614 Param->setDefaultArg(0);
615 }
616 }
617 }
618}
Douglas Gregor556877c2008-04-13 21:30:24 +0000619
Richard Smitheb3c10c2011-10-01 02:31:28 +0000620// CheckConstexprParameterTypes - Check whether a function's parameter types
621// are all literal types. If so, return true. If not, produce a suitable
622// diagnostic depending on @p CCK and return false.
623static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
624 Sema::CheckConstexprKind CCK) {
625 unsigned ArgIndex = 0;
626 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
627 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
628 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
629 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
630 SourceLocation ParamLoc = PD->getLocation();
631 if (!(*i)->isDependentType() &&
632 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
633 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
634 << ArgIndex+1 << PD->getSourceRange()
635 << isa<CXXConstructorDecl>(FD) :
636 SemaRef.PDiag(),
637 /*AllowIncompleteType*/ true)) {
638 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
639 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
640 << ArgIndex+1 << PD->getSourceRange()
641 << isa<CXXConstructorDecl>(FD) << *i;
642 return false;
643 }
644 }
645 return true;
646}
647
648// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
649// the requirements of a constexpr function declaration or a constexpr
650// constructor declaration. Return true if it does, false if not.
651//
Richard Smith7971b692012-01-13 04:54:00 +0000652// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000653//
654// \param CCK Specifies whether to produce diagnostics if the function does not
655// satisfy the requirements.
656bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
657 CheckConstexprKind CCK) {
658 assert((CCK != CCK_NoteNonConstexprInstantiation ||
659 (NewFD->getTemplateInstantiationPattern() &&
660 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
661 "only constexpr templates can be instantiated non-constexpr");
662
Richard Smith7971b692012-01-13 04:54:00 +0000663 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
664 if (MD && MD->isInstance()) {
665 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smitheb3c10c2011-10-01 02:31:28 +0000666 // In addition, either its function-body shall be = delete or = default or
667 // it shall satisfy the following constraints:
668 // - the class shall not have any virtual base classes;
Richard Smith7971b692012-01-13 04:54:00 +0000669 //
670 // We apply this to constexpr member functions too: the class cannot be a
671 // literal type, so the members are not permitted to be constexpr.
672 const CXXRecordDecl *RD = MD->getParent();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000673 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)
Richard Smith7971b692012-01-13 04:54:00 +0000682 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
683 << RD->getNumVBases();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000684 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
685 E = RD->vbases_end(); I != E; ++I)
686 Diag(I->getSourceRange().getBegin(),
687 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
688 }
689 return false;
690 }
Richard Smith7971b692012-01-13 04:54:00 +0000691 }
692
693 if (!isa<CXXConstructorDecl>(NewFD)) {
694 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000695 // The definition of a constexpr function shall satisfy the following
696 // constraints:
697 // - it shall not be virtual;
698 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
699 if (Method && Method->isVirtual()) {
700 if (CCK != CCK_Instantiation) {
701 Diag(NewFD->getLocation(),
702 CCK == CCK_Declaration ? diag::err_constexpr_virtual
703 : diag::note_constexpr_tmpl_virtual);
704
705 // If it's not obvious why this function is virtual, find an overridden
706 // function which uses the 'virtual' keyword.
707 const CXXMethodDecl *WrittenVirtual = Method;
708 while (!WrittenVirtual->isVirtualAsWritten())
709 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
710 if (WrittenVirtual != Method)
Richard Smith7971b692012-01-13 04:54:00 +0000711 Diag(WrittenVirtual->getLocation(),
Richard Smitheb3c10c2011-10-01 02:31:28 +0000712 diag::note_overridden_virtual_function);
713 }
714 return false;
715 }
716
717 // - its return type shall be a literal type;
718 QualType RT = NewFD->getResultType();
719 if (!RT->isDependentType() &&
720 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
721 PDiag(diag::err_constexpr_non_literal_return) :
722 PDiag(),
723 /*AllowIncompleteType*/ true)) {
724 if (CCK == CCK_NoteNonConstexprInstantiation)
725 Diag(NewFD->getLocation(),
726 diag::note_constexpr_tmpl_non_literal_return) << RT;
727 return false;
728 }
Richard Smitheb3c10c2011-10-01 02:31:28 +0000729 }
730
Richard Smith7971b692012-01-13 04:54:00 +0000731 // - each of its parameter types shall be a literal type;
732 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
733 return false;
734
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 return true;
736}
737
738/// Check the given declaration statement is legal within a constexpr function
739/// body. C++0x [dcl.constexpr]p3,p4.
740///
741/// \return true if the body is OK, false if we have diagnosed a problem.
742static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
743 DeclStmt *DS) {
744 // C++0x [dcl.constexpr]p3 and p4:
745 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
746 // contain only
747 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
748 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
749 switch ((*DclIt)->getKind()) {
750 case Decl::StaticAssert:
751 case Decl::Using:
752 case Decl::UsingShadow:
753 case Decl::UsingDirective:
754 case Decl::UnresolvedUsingTypename:
755 // - static_assert-declarations
756 // - using-declarations,
757 // - using-directives,
758 continue;
759
760 case Decl::Typedef:
761 case Decl::TypeAlias: {
762 // - typedef declarations and alias-declarations that do not define
763 // classes or enumerations,
764 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
765 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
766 // Don't allow variably-modified types in constexpr functions.
767 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
768 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
769 << TL.getSourceRange() << TL.getType()
770 << isa<CXXConstructorDecl>(Dcl);
771 return false;
772 }
773 continue;
774 }
775
776 case Decl::Enum:
777 case Decl::CXXRecord:
778 // As an extension, we allow the declaration (but not the definition) of
779 // classes and enumerations in all declarations, not just in typedef and
780 // alias declarations.
781 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
782 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
783 << isa<CXXConstructorDecl>(Dcl);
784 return false;
785 }
786 continue;
787
788 case Decl::Var:
789 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
790 << isa<CXXConstructorDecl>(Dcl);
791 return false;
792
793 default:
794 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
795 << isa<CXXConstructorDecl>(Dcl);
796 return false;
797 }
798 }
799
800 return true;
801}
802
803/// Check that the given field is initialized within a constexpr constructor.
804///
805/// \param Dcl The constexpr constructor being checked.
806/// \param Field The field being checked. This may be a member of an anonymous
807/// struct or union nested within the class being checked.
808/// \param Inits All declarations, including anonymous struct/union members and
809/// indirect members, for which any initialization was provided.
810/// \param Diagnosed Set to true if an error is produced.
811static void CheckConstexprCtorInitializer(Sema &SemaRef,
812 const FunctionDecl *Dcl,
813 FieldDecl *Field,
814 llvm::SmallSet<Decl*, 16> &Inits,
815 bool &Diagnosed) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000816 if (Field->isUnnamedBitfield())
817 return;
818
Richard Smitheb3c10c2011-10-01 02:31:28 +0000819 if (!Inits.count(Field)) {
820 if (!Diagnosed) {
821 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
822 Diagnosed = true;
823 }
824 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
825 } else if (Field->isAnonymousStructOrUnion()) {
826 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
827 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
828 I != E; ++I)
829 // If an anonymous union contains an anonymous struct of which any member
830 // is initialized, all members must be initialized.
831 if (!RD->isUnion() || Inits.count(*I))
832 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
833 }
834}
835
836/// Check the body for the given constexpr function declaration only contains
837/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
838///
839/// \return true if the body is OK, false if we have diagnosed a problem.
840bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
841 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +0000842 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000843 // The definition of a constexpr function shall satisfy the following
844 // constraints: [...]
845 // - its function-body shall be = delete, = default, or a
846 // compound-statement
847 //
Richard Smith74388b42012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000849 // In the definition of a constexpr constructor, [...]
850 // - its function-body shall not be a function-try-block;
851 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
852 << isa<CXXConstructorDecl>(Dcl);
853 return false;
854 }
855
856 // - its function-body shall be [...] a compound-statement that contains only
857 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
858
859 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
860 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
861 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
862 switch ((*BodyIt)->getStmtClass()) {
863 case Stmt::NullStmtClass:
864 // - null statements,
865 continue;
866
867 case Stmt::DeclStmtClass:
868 // - static_assert-declarations
869 // - using-declarations,
870 // - using-directives,
871 // - typedef declarations and alias-declarations that do not define
872 // classes or enumerations,
873 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
874 return false;
875 continue;
876
877 case Stmt::ReturnStmtClass:
878 // - and exactly one return statement;
879 if (isa<CXXConstructorDecl>(Dcl))
880 break;
881
882 ReturnStmts.push_back((*BodyIt)->getLocStart());
883 // FIXME
884 // - every constructor call and implicit conversion used in initializing
885 // the return value shall be one of those allowed in a constant
886 // expression.
887 // Deal with this as part of a general check that the function can produce
888 // a constant expression (for [dcl.constexpr]p5).
889 continue;
890
891 default:
892 break;
893 }
894
895 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
896 << isa<CXXConstructorDecl>(Dcl);
897 return false;
898 }
899
900 if (const CXXConstructorDecl *Constructor
901 = dyn_cast<CXXConstructorDecl>(Dcl)) {
902 const CXXRecordDecl *RD = Constructor->getParent();
903 // - every non-static data member and base class sub-object shall be
904 // initialized;
905 if (RD->isUnion()) {
906 // DR1359: Exactly one member of a union shall be initialized.
907 if (Constructor->getNumCtorInitializers() == 0) {
908 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
909 return false;
910 }
Richard Smithf368fb42011-10-10 16:38:04 +0000911 } else if (!Constructor->isDependentContext() &&
912 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000913 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
914
915 // Skip detailed checking if we have enough initializers, and we would
916 // allow at most one initializer per member.
917 bool AnyAnonStructUnionMembers = false;
918 unsigned Fields = 0;
919 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
920 E = RD->field_end(); I != E; ++I, ++Fields) {
921 if ((*I)->isAnonymousStructOrUnion()) {
922 AnyAnonStructUnionMembers = true;
923 break;
924 }
925 }
926 if (AnyAnonStructUnionMembers ||
927 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
928 // Check initialization of non-static data members. Base classes are
929 // always initialized so do not need to be checked. Dependent bases
930 // might not have initializers in the member initializer list.
931 llvm::SmallSet<Decl*, 16> Inits;
932 for (CXXConstructorDecl::init_const_iterator
933 I = Constructor->init_begin(), E = Constructor->init_end();
934 I != E; ++I) {
935 if (FieldDecl *FD = (*I)->getMember())
936 Inits.insert(FD);
937 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
938 Inits.insert(ID->chain_begin(), ID->chain_end());
939 }
940
941 bool Diagnosed = false;
942 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
943 E = RD->field_end(); I != E; ++I)
944 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
945 if (Diagnosed)
946 return false;
947 }
948 }
949
950 // FIXME
951 // - every constructor involved in initializing non-static data members
952 // and base class sub-objects shall be a constexpr constructor;
953 // - every assignment-expression that is an initializer-clause appearing
954 // directly or indirectly within a brace-or-equal-initializer for
955 // a non-static data member that is not named by a mem-initializer-id
956 // shall be a constant expression; and
957 // - every implicit conversion used in converting a constructor argument
958 // to the corresponding parameter type and converting
959 // a full-expression to the corresponding member type shall be one of
960 // those allowed in a constant expression.
961 // Deal with these as part of a general check that the function can produce
962 // a constant expression (for [dcl.constexpr]p5).
963 } else {
964 if (ReturnStmts.empty()) {
965 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
966 return false;
967 }
968 if (ReturnStmts.size() > 1) {
969 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
970 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
971 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
972 return false;
973 }
974 }
975
Richard Smith74388b42012-02-04 00:33:54 +0000976 // C++11 [dcl.constexpr]p5:
977 // if no function argument values exist such that the function invocation
978 // substitution would produce a constant expression, the program is
979 // ill-formed; no diagnostic required.
980 // C++11 [dcl.constexpr]p3:
981 // - every constructor call and implicit conversion used in initializing the
982 // return value shall be one of those allowed in a constant expression.
983 // C++11 [dcl.constexpr]p4:
984 // - every constructor involved in initializing non-static data members and
985 // base class sub-objects shall be a constexpr constructor.
986 //
987 // FIXME: We currently disable this check inside system headers, to work
988 // around early STL implementations which contain constexpr functions which
989 // can't produce constant expressions.
Richard Smith253c2a32012-01-27 01:14:48 +0000990 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith74388b42012-02-04 00:33:54 +0000991 if (!Context.getSourceManager().isInSystemHeader(Dcl->getLocation()) &&
992 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith253c2a32012-01-27 01:14:48 +0000993 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
994 << isa<CXXConstructorDecl>(Dcl);
995 for (size_t I = 0, N = Diags.size(); I != N; ++I)
996 Diag(Diags[I].first, Diags[I].second);
997 return false;
998 }
999
Richard Smitheb3c10c2011-10-01 02:31:28 +00001000 return true;
1001}
1002
Douglas Gregor61956c42008-10-31 09:07:45 +00001003/// isCurrentClassName - Determine whether the identifier II is the
1004/// name of the class type currently being defined. In the case of
1005/// nested classes, this will only return true if II is the name of
1006/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001007bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1008 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001009 assert(getLangOptions().CPlusPlus && "No class names in C!");
1010
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001011 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001012 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001013 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001014 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1015 } else
1016 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1017
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001018 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001019 return &II == CurDecl->getIdentifier();
1020 else
1021 return false;
1022}
1023
Mike Stump11289f42009-09-09 15:08:12 +00001024/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001025///
1026/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1027/// and returns NULL otherwise.
1028CXXBaseSpecifier *
1029Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1030 SourceRange SpecifierRange,
1031 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001032 TypeSourceInfo *TInfo,
1033 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001034 QualType BaseType = TInfo->getType();
1035
Douglas Gregor463421d2009-03-03 04:44:36 +00001036 // C++ [class.union]p1:
1037 // A union shall not have base classes.
1038 if (Class->isUnion()) {
1039 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1040 << SpecifierRange;
1041 return 0;
1042 }
1043
Douglas Gregor752a5952011-01-03 22:36:02 +00001044 if (EllipsisLoc.isValid() &&
1045 !TInfo->getType()->containsUnexpandedParameterPack()) {
1046 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1047 << TInfo->getTypeLoc().getSourceRange();
1048 EllipsisLoc = SourceLocation();
1049 }
1050
Douglas Gregor463421d2009-03-03 04:44:36 +00001051 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +00001052 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001053 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001054 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001055
1056 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +00001057
1058 // Base specifiers must be record types.
1059 if (!BaseType->isRecordType()) {
1060 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1061 return 0;
1062 }
1063
1064 // C++ [class.union]p1:
1065 // A union shall not be used as a base class.
1066 if (BaseType->isUnionType()) {
1067 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1068 return 0;
1069 }
1070
1071 // C++ [class.derived]p2:
1072 // The class-name in a base-specifier shall not be an incompletely
1073 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001074 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00001075 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +00001076 << SpecifierRange)) {
1077 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001078 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001079 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001080
Eli Friedmanc96d4962009-08-15 21:55:26 +00001081 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001082 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001083 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001084 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001085 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +00001086 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1087 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001088
Anders Carlsson65c76d32011-03-25 14:55:14 +00001089 // C++ [class]p3:
1090 // If a class is marked final and it appears as a base-type-specifier in
1091 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001092 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001093 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1094 << CXXBaseDecl->getDeclName();
1095 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1096 << CXXBaseDecl->getDeclName();
1097 return 0;
1098 }
1099
John McCall3696dcb2010-08-17 07:23:57 +00001100 if (BaseDecl->isInvalidDecl())
1101 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001102
1103 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001104 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001105 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001106 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001107}
1108
Douglas Gregor556877c2008-04-13 21:30:24 +00001109/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1110/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001111/// example:
1112/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001113/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001114BaseResult
John McCall48871652010-08-21 09:40:31 +00001115Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +00001116 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001117 ParsedType basetype, SourceLocation BaseLoc,
1118 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001119 if (!classdecl)
1120 return true;
1121
Douglas Gregorc40290e2009-03-09 23:48:35 +00001122 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001123 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001124 if (!Class)
1125 return true;
1126
Nick Lewycky19b9f952010-07-26 16:56:01 +00001127 TypeSourceInfo *TInfo = 0;
1128 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001129
Douglas Gregor752a5952011-01-03 22:36:02 +00001130 if (EllipsisLoc.isInvalid() &&
1131 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001132 UPPC_BaseType))
1133 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001134
Douglas Gregor463421d2009-03-03 04:44:36 +00001135 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001136 Virtual, Access, TInfo,
1137 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001138 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +00001139
Douglas Gregor463421d2009-03-03 04:44:36 +00001140 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001141}
Douglas Gregor556877c2008-04-13 21:30:24 +00001142
Douglas Gregor463421d2009-03-03 04:44:36 +00001143/// \brief Performs the actual work of attaching the given base class
1144/// specifiers to a C++ class.
1145bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1146 unsigned NumBases) {
1147 if (NumBases == 0)
1148 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001149
1150 // Used to keep track of which base types we have already seen, so
1151 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001152 // that the key is always the unqualified canonical type of the base
1153 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001154 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1155
1156 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001157 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001158 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001159 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001160 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001161 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001162 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +00001163 if (KnownBaseTypes[NewBaseType]) {
1164 // C++ [class.mi]p3:
1165 // A class shall not be specified as a direct base class of a
1166 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +00001167 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001168 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001169 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001170 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001171
1172 // Delete the duplicate base class specifier; we're going to
1173 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001174 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001175
1176 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001177 } else {
1178 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +00001179 KnownBaseTypes[NewBaseType] = Bases[idx];
1180 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian28f5fb92011-10-24 17:30:45 +00001181 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian47f9a732011-10-21 22:27:12 +00001182 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1183 if (RD->hasAttr<WeakAttr>())
1184 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregor29a92472008-10-22 17:49:05 +00001185 }
1186 }
1187
1188 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001189 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001190
1191 // Delete the remaining (good) base class specifiers, since their
1192 // data has been copied into the CXXRecordDecl.
1193 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001194 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001195
1196 return Invalid;
1197}
1198
1199/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1200/// class, after checking whether there are any duplicate base
1201/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001202void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001203 unsigned NumBases) {
1204 if (!ClassDecl || !Bases || !NumBases)
1205 return;
1206
1207 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001208 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001209 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001210}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001211
John McCalle78aac42010-03-10 03:28:59 +00001212static CXXRecordDecl *GetClassForType(QualType T) {
1213 if (const RecordType *RT = T->getAs<RecordType>())
1214 return cast<CXXRecordDecl>(RT->getDecl());
1215 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1216 return ICT->getDecl();
1217 else
1218 return 0;
1219}
1220
Douglas Gregor36d1b142009-10-06 17:59:45 +00001221/// \brief Determine whether the type \p Derived is a C++ class that is
1222/// derived from the type \p Base.
1223bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1224 if (!getLangOptions().CPlusPlus)
1225 return false;
John McCalle78aac42010-03-10 03:28:59 +00001226
1227 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1228 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001229 return false;
1230
John McCalle78aac42010-03-10 03:28:59 +00001231 CXXRecordDecl *BaseRD = GetClassForType(Base);
1232 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001233 return false;
1234
John McCall67da35c2010-02-04 22:26:26 +00001235 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1236 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001237}
1238
1239/// \brief Determine whether the type \p Derived is a C++ class that is
1240/// derived from the type \p Base.
1241bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1242 if (!getLangOptions().CPlusPlus)
1243 return false;
1244
John McCalle78aac42010-03-10 03:28:59 +00001245 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1246 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001247 return false;
1248
John McCalle78aac42010-03-10 03:28:59 +00001249 CXXRecordDecl *BaseRD = GetClassForType(Base);
1250 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001251 return false;
1252
Douglas Gregor36d1b142009-10-06 17:59:45 +00001253 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1254}
1255
Anders Carlssona70cff62010-04-24 19:06:50 +00001256void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001257 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001258 assert(BasePathArray.empty() && "Base path array must be empty!");
1259 assert(Paths.isRecordingPaths() && "Must record paths!");
1260
1261 const CXXBasePath &Path = Paths.front();
1262
1263 // We first go backward and check if we have a virtual base.
1264 // FIXME: It would be better if CXXBasePath had the base specifier for
1265 // the nearest virtual base.
1266 unsigned Start = 0;
1267 for (unsigned I = Path.size(); I != 0; --I) {
1268 if (Path[I - 1].Base->isVirtual()) {
1269 Start = I - 1;
1270 break;
1271 }
1272 }
1273
1274 // Now add all bases.
1275 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001276 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001277}
1278
Douglas Gregor88d292c2010-05-13 16:44:06 +00001279/// \brief Determine whether the given base path includes a virtual
1280/// base class.
John McCallcf142162010-08-07 06:22:56 +00001281bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1282 for (CXXCastPath::const_iterator B = BasePath.begin(),
1283 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001284 B != BEnd; ++B)
1285 if ((*B)->isVirtual())
1286 return true;
1287
1288 return false;
1289}
1290
Douglas Gregor36d1b142009-10-06 17:59:45 +00001291/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1292/// conversion (where Derived and Base are class types) is
1293/// well-formed, meaning that the conversion is unambiguous (and
1294/// that all of the base classes are accessible). Returns true
1295/// and emits a diagnostic if the code is ill-formed, returns false
1296/// otherwise. Loc is the location where this routine should point to
1297/// if there is an error, and Range is the source range to highlight
1298/// if there is an error.
1299bool
1300Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001301 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001302 unsigned AmbigiousBaseConvID,
1303 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001304 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001305 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001306 // First, determine whether the path from Derived to Base is
1307 // ambiguous. This is slightly more expensive than checking whether
1308 // the Derived to Base conversion exists, because here we need to
1309 // explore multiple paths to determine if there is an ambiguity.
1310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1311 /*DetectVirtual=*/false);
1312 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1313 assert(DerivationOkay &&
1314 "Can only be used with a derived-to-base conversion");
1315 (void)DerivationOkay;
1316
1317 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001318 if (InaccessibleBaseID) {
1319 // Check that the base class can be accessed.
1320 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1321 InaccessibleBaseID)) {
1322 case AR_inaccessible:
1323 return true;
1324 case AR_accessible:
1325 case AR_dependent:
1326 case AR_delayed:
1327 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001328 }
John McCall5b0829a2010-02-10 09:31:12 +00001329 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001330
1331 // Build a base path if necessary.
1332 if (BasePath)
1333 BuildBasePathArray(Paths, *BasePath);
1334 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001335 }
1336
1337 // We know that the derived-to-base conversion is ambiguous, and
1338 // we're going to produce a diagnostic. Perform the derived-to-base
1339 // search just one more time to compute all of the possible paths so
1340 // that we can print them out. This is more expensive than any of
1341 // the previous derived-to-base checks we've done, but at this point
1342 // performance isn't as much of an issue.
1343 Paths.clear();
1344 Paths.setRecordingPaths(true);
1345 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1346 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1347 (void)StillOkay;
1348
1349 // Build up a textual representation of the ambiguous paths, e.g.,
1350 // D -> B -> A, that will be used to illustrate the ambiguous
1351 // conversions in the diagnostic. We only print one of the paths
1352 // to each base class subobject.
1353 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1354
1355 Diag(Loc, AmbigiousBaseConvID)
1356 << Derived << Base << PathDisplayStr << Range << Name;
1357 return true;
1358}
1359
1360bool
1361Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001362 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001363 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001364 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001365 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001366 IgnoreAccess ? 0
1367 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001368 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001369 Loc, Range, DeclarationName(),
1370 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001371}
1372
1373
1374/// @brief Builds a string representing ambiguous paths from a
1375/// specific derived class to different subobjects of the same base
1376/// class.
1377///
1378/// This function builds a string that can be used in error messages
1379/// to show the different paths that one can take through the
1380/// inheritance hierarchy to go from the derived class to different
1381/// subobjects of a base class. The result looks something like this:
1382/// @code
1383/// struct D -> struct B -> struct A
1384/// struct D -> struct C -> struct A
1385/// @endcode
1386std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1387 std::string PathDisplayStr;
1388 std::set<unsigned> DisplayedPaths;
1389 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1390 Path != Paths.end(); ++Path) {
1391 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1392 // We haven't displayed a path to this particular base
1393 // class subobject yet.
1394 PathDisplayStr += "\n ";
1395 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1396 for (CXXBasePath::const_iterator Element = Path->begin();
1397 Element != Path->end(); ++Element)
1398 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1399 }
1400 }
1401
1402 return PathDisplayStr;
1403}
1404
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001405//===----------------------------------------------------------------------===//
1406// C++ class member Handling
1407//===----------------------------------------------------------------------===//
1408
Abramo Bagnarad7340582010-06-05 05:09:32 +00001409/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001410bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1411 SourceLocation ASLoc,
1412 SourceLocation ColonLoc,
1413 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001414 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001415 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001416 ASLoc, ColonLoc);
1417 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001418 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001419}
1420
Anders Carlssonfd835532011-01-20 05:57:14 +00001421/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001422void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001423 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001424 if (!MD || !MD->isVirtual())
1425 return;
1426
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001427 if (MD->isDependentContext())
1428 return;
1429
Anders Carlssonfd835532011-01-20 05:57:14 +00001430 // C++0x [class.virtual]p3:
1431 // If a virtual function is marked with the virt-specifier override and does
1432 // not override a member function of a base class,
1433 // the program is ill-formed.
1434 bool HasOverriddenMethods =
1435 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001436 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001437 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001438 diag::err_function_marked_override_not_overriding)
1439 << MD->getDeclName();
1440 return;
1441 }
1442}
1443
Anders Carlsson3f610c72011-01-20 16:25:36 +00001444/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1445/// function overrides a virtual member function marked 'final', according to
1446/// C++0x [class.virtual]p3.
1447bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1448 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001449 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001450 return false;
1451
1452 Diag(New->getLocation(), diag::err_final_function_overridden)
1453 << New->getDeclName();
1454 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1455 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001456}
1457
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001458/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1459/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001460/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1461/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1462/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001463Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001464Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001465 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001466 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001467 bool HasDeferredInit) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001468 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001469 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1470 DeclarationName Name = NameInfo.getName();
1471 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001472
1473 // For anonymous bitfields, the location should point to the type.
1474 if (Loc.isInvalid())
1475 Loc = D.getSourceRange().getBegin();
1476
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001477 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001478
John McCallb1cd7da2010-06-04 08:34:12 +00001479 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001480 assert(!DS.isFriendSpecified());
1481
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001482 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001483
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001484 // C++ 9.2p6: A member shall not be declared to have automatic storage
1485 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001486 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1487 // data members and cannot be applied to names declared const or static,
1488 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001489 switch (DS.getStorageClassSpec()) {
1490 case DeclSpec::SCS_unspecified:
1491 case DeclSpec::SCS_typedef:
1492 case DeclSpec::SCS_static:
1493 // FALL THROUGH.
1494 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001495 case DeclSpec::SCS_mutable:
1496 if (isFunc) {
1497 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001498 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001499 else
Chris Lattner3b054132008-11-19 05:08:23 +00001500 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Sebastian Redl8071edb2008-11-17 23:24:37 +00001502 // FIXME: It would be nicer if the keyword was ignored only for this
1503 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001504 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001505 }
1506 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001507 default:
1508 if (DS.getStorageClassSpecLoc().isValid())
1509 Diag(DS.getStorageClassSpecLoc(),
1510 diag::err_storageclass_invalid_for_member);
1511 else
1512 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1513 D.getMutableDeclSpec().ClearStorageClassSpecs();
1514 }
1515
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001516 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1517 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001518 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001519
1520 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001521 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001522 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001523
1524 // Data members must have identifiers for names.
1525 if (Name.getNameKind() != DeclarationName::Identifier) {
1526 Diag(Loc, diag::err_bad_variable_name)
1527 << Name;
1528 return 0;
1529 }
Douglas Gregora007d362010-10-13 22:19:53 +00001530
Douglas Gregor7c26c042011-09-21 14:40:46 +00001531 IdentifierInfo *II = Name.getAsIdentifierInfo();
1532
1533 // Member field could not be with "template" keyword.
1534 // So TemplateParameterLists should be empty in this case.
1535 if (TemplateParameterLists.size()) {
1536 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1537 if (TemplateParams->size()) {
1538 // There is no such thing as a member field template.
1539 Diag(D.getIdentifierLoc(), diag::err_template_member)
1540 << II
1541 << SourceRange(TemplateParams->getTemplateLoc(),
1542 TemplateParams->getRAngleLoc());
1543 } else {
1544 // There is an extraneous 'template<>' for this member.
1545 Diag(TemplateParams->getTemplateLoc(),
1546 diag::err_template_member_noparams)
1547 << II
1548 << SourceRange(TemplateParams->getTemplateLoc(),
1549 TemplateParams->getRAngleLoc());
1550 }
1551 return 0;
1552 }
1553
Douglas Gregora007d362010-10-13 22:19:53 +00001554 if (SS.isSet() && !SS.isInvalid()) {
1555 // The user provided a superfluous scope specifier inside a class
1556 // definition:
1557 //
1558 // class X {
1559 // int X::member;
1560 // };
1561 DeclContext *DC = 0;
1562 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1563 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001564 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregora007d362010-10-13 22:19:53 +00001565 else
1566 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1567 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001568
Douglas Gregora007d362010-10-13 22:19:53 +00001569 SS.clear();
1570 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001571
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001572 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001573 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001574 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001575 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001576 assert(!HasDeferredInit);
1577
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001578 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner97e277e2009-03-05 23:03:49 +00001579 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001580 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001581 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001582
1583 // Non-instance-fields can't have a bitfield.
1584 if (BitWidth) {
1585 if (Member->isInvalidDecl()) {
1586 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001587 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001588 // C++ 9.6p3: A bit-field shall not be a static member.
1589 // "static member 'A' cannot be a bit-field"
1590 Diag(Loc, diag::err_static_not_bitfield)
1591 << Name << BitWidth->getSourceRange();
1592 } else if (isa<TypedefDecl>(Member)) {
1593 // "typedef member 'x' cannot be a bit-field"
1594 Diag(Loc, diag::err_typedef_not_bitfield)
1595 << Name << BitWidth->getSourceRange();
1596 } else {
1597 // A function typedef ("typedef int f(); f a;").
1598 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1599 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001600 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001601 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001602 }
Mike Stump11289f42009-09-09 15:08:12 +00001603
Chris Lattnerd26760a2009-03-05 23:01:03 +00001604 BitWidth = 0;
1605 Member->setInvalidDecl();
1606 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001607
1608 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Douglas Gregor3447e762009-08-20 22:52:58 +00001610 // If we have declared a member function template, set the access of the
1611 // templated declaration as well.
1612 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1613 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001614 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001615
Anders Carlsson13a69102011-01-20 04:34:22 +00001616 if (VS.isOverrideSpecified()) {
1617 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1618 if (!MD || !MD->isVirtual()) {
1619 Diag(Member->getLocStart(),
1620 diag::override_keyword_only_allowed_on_virtual_member_functions)
1621 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001622 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001623 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001624 }
1625 if (VS.isFinalSpecified()) {
1626 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1627 if (!MD || !MD->isVirtual()) {
1628 Diag(Member->getLocStart(),
1629 diag::override_keyword_only_allowed_on_virtual_member_functions)
1630 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001631 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001632 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001633 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001634
Douglas Gregorf2f08062011-03-08 17:10:18 +00001635 if (VS.getLastLocation().isValid()) {
1636 // Update the end location of a method that has a virt-specifiers.
1637 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1638 MD->setRangeEnd(VS.getLastLocation());
1639 }
1640
Anders Carlssonc87f8612011-01-20 06:29:02 +00001641 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001642
Douglas Gregor92751d42008-11-17 22:58:34 +00001643 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001644
John McCall25849ca2011-02-15 07:12:36 +00001645 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001646 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001647 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001648}
1649
Richard Smith938f40b2011-06-11 17:19:42 +00001650/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001651/// in-class initializer for a non-static C++ class member, and after
1652/// instantiating an in-class initializer in a class template. Such actions
1653/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001654void
1655Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1656 Expr *InitExpr) {
1657 FieldDecl *FD = cast<FieldDecl>(D);
1658
1659 if (!InitExpr) {
1660 FD->setInvalidDecl();
1661 FD->removeInClassInitializer();
1662 return;
1663 }
1664
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00001665 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1666 FD->setInvalidDecl();
1667 FD->removeInClassInitializer();
1668 return;
1669 }
1670
Richard Smith938f40b2011-06-11 17:19:42 +00001671 ExprResult Init = InitExpr;
1672 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1673 // FIXME: if there is no EqualLoc, this is list-initialization.
1674 Init = PerformCopyInitialization(
1675 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1676 if (Init.isInvalid()) {
1677 FD->setInvalidDecl();
1678 return;
1679 }
1680
1681 CheckImplicitConversions(Init.get(), EqualLoc);
1682 }
1683
1684 // C++0x [class.base.init]p7:
1685 // The initialization of each base and member constitutes a
1686 // full-expression.
1687 Init = MaybeCreateExprWithCleanups(Init);
1688 if (Init.isInvalid()) {
1689 FD->setInvalidDecl();
1690 return;
1691 }
1692
1693 InitExpr = Init.release();
1694
1695 FD->setInClassInitializer(InitExpr);
1696}
1697
Douglas Gregor15e77a22009-12-31 09:10:24 +00001698/// \brief Find the direct and/or virtual base specifiers that
1699/// correspond to the given base type, for use in base initialization
1700/// within a constructor.
1701static bool FindBaseInitializer(Sema &SemaRef,
1702 CXXRecordDecl *ClassDecl,
1703 QualType BaseType,
1704 const CXXBaseSpecifier *&DirectBaseSpec,
1705 const CXXBaseSpecifier *&VirtualBaseSpec) {
1706 // First, check for a direct base class.
1707 DirectBaseSpec = 0;
1708 for (CXXRecordDecl::base_class_const_iterator Base
1709 = ClassDecl->bases_begin();
1710 Base != ClassDecl->bases_end(); ++Base) {
1711 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1712 // We found a direct base of this type. That's what we're
1713 // initializing.
1714 DirectBaseSpec = &*Base;
1715 break;
1716 }
1717 }
1718
1719 // Check for a virtual base class.
1720 // FIXME: We might be able to short-circuit this if we know in advance that
1721 // there are no virtual bases.
1722 VirtualBaseSpec = 0;
1723 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1724 // We haven't found a base yet; search the class hierarchy for a
1725 // virtual base class.
1726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1727 /*DetectVirtual=*/false);
1728 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1729 BaseType, Paths)) {
1730 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1731 Path != Paths.end(); ++Path) {
1732 if (Path->back().Base->isVirtual()) {
1733 VirtualBaseSpec = Path->back().Base;
1734 break;
1735 }
1736 }
1737 }
1738 }
1739
1740 return DirectBaseSpec || VirtualBaseSpec;
1741}
1742
Sebastian Redla74948d2011-09-24 17:48:25 +00001743/// \brief Handle a C++ member initializer using braced-init-list syntax.
1744MemInitResult
1745Sema::ActOnMemInitializer(Decl *ConstructorD,
1746 Scope *S,
1747 CXXScopeSpec &SS,
1748 IdentifierInfo *MemberOrBase,
1749 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001750 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001751 SourceLocation IdLoc,
1752 Expr *InitList,
1753 SourceLocation EllipsisLoc) {
1754 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001755 DS, IdLoc, MultiInitializer(InitList),
1756 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00001757}
1758
1759/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001760MemInitResult
John McCall48871652010-08-21 09:40:31 +00001761Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001762 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001763 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001764 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001765 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001766 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001767 SourceLocation IdLoc,
1768 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001769 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001770 SourceLocation RParenLoc,
1771 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001772 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001773 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1774 NumArgs, RParenLoc),
Sebastian Redla74948d2011-09-24 17:48:25 +00001775 EllipsisLoc);
1776}
1777
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001778namespace {
1779
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00001780// Callback to only accept typo corrections that can be a valid C++ member
1781// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001782class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1783 public:
1784 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1785 : ClassDecl(ClassDecl) {}
1786
1787 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1788 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1789 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1790 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1791 else
1792 return isa<TypeDecl>(ND);
1793 }
1794 return false;
1795 }
1796
1797 private:
1798 CXXRecordDecl *ClassDecl;
1799};
1800
1801}
1802
Sebastian Redla74948d2011-09-24 17:48:25 +00001803/// \brief Handle a C++ member initializer.
1804MemInitResult
1805Sema::BuildMemInitializer(Decl *ConstructorD,
1806 Scope *S,
1807 CXXScopeSpec &SS,
1808 IdentifierInfo *MemberOrBase,
1809 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001810 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001811 SourceLocation IdLoc,
1812 const MultiInitializer &Args,
1813 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001814 if (!ConstructorD)
1815 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001817 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001818
1819 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001820 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001821 if (!Constructor) {
1822 // The user wrote a constructor initializer on a function that is
1823 // not a C++ constructor. Ignore the error for now, because we may
1824 // have more member initializers coming; we'll diagnose it just
1825 // once in ActOnMemInitializers.
1826 return true;
1827 }
1828
1829 CXXRecordDecl *ClassDecl = Constructor->getParent();
1830
1831 // C++ [class.base.init]p2:
1832 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001833 // constructor's class and, if not found in that scope, are looked
1834 // up in the scope containing the constructor's definition.
1835 // [Note: if the constructor's class contains a member with the
1836 // same name as a direct or virtual base class of the class, a
1837 // mem-initializer-id naming the member or base class and composed
1838 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001839 // mem-initializer-id for the hidden base class may be specified
1840 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001841 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001842 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00001843 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001844 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001845 if (Result.first != Result.second) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00001846 ValueDecl *Member;
1847 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1848 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00001849 if (EllipsisLoc.isValid())
1850 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001851 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1852
1853 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001854 }
Francois Pichetd583da02010-12-04 09:14:42 +00001855 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001856 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001857 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001858 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001859 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001860
1861 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001862 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00001863 } else if (DS.getTypeSpecType() == TST_decltype) {
1864 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00001865 } else {
1866 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1867 LookupParsedName(R, S, &SS);
1868
1869 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1870 if (!TyD) {
1871 if (R.isAmbiguous()) return true;
1872
John McCallda6841b2010-04-09 19:01:14 +00001873 // We don't want access-control diagnostics here.
1874 R.suppressDiagnostics();
1875
Douglas Gregora3b624a2010-01-19 06:46:48 +00001876 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1877 bool NotUnknownSpecialization = false;
1878 DeclContext *DC = computeDeclContext(SS, false);
1879 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1880 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1881
1882 if (!NotUnknownSpecialization) {
1883 // When the scope specifier can refer to a member of an unknown
1884 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001885 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1886 SS.getWithLocInContext(Context),
1887 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001888 if (BaseType.isNull())
1889 return true;
1890
Douglas Gregora3b624a2010-01-19 06:46:48 +00001891 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001892 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001893 }
1894 }
1895
Douglas Gregor15e77a22009-12-31 09:10:24 +00001896 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001897 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001898 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001899 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001900 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001901 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001902 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1903 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1904 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001905 // We have found a non-static data member with a similar
1906 // name to what was typed; complain and initialize that
1907 // member.
1908 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1909 << MemberOrBase << true << CorrectedQuotedStr
1910 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1911 Diag(Member->getLocation(), diag::note_previous_decl)
1912 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001913
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001914 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001915 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001916 const CXXBaseSpecifier *DirectBaseSpec;
1917 const CXXBaseSpecifier *VirtualBaseSpec;
1918 if (FindBaseInitializer(*this, ClassDecl,
1919 Context.getTypeDeclType(Type),
1920 DirectBaseSpec, VirtualBaseSpec)) {
1921 // We have found a direct or virtual base class with a
1922 // similar name to what was typed; complain and initialize
1923 // that base class.
1924 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001925 << MemberOrBase << false << CorrectedQuotedStr
1926 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001927
1928 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1929 : VirtualBaseSpec;
1930 Diag(BaseSpec->getSourceRange().getBegin(),
1931 diag::note_base_class_specified_here)
1932 << BaseSpec->getType()
1933 << BaseSpec->getSourceRange();
1934
Douglas Gregor15e77a22009-12-31 09:10:24 +00001935 TyD = Type;
1936 }
1937 }
1938 }
1939
Douglas Gregora3b624a2010-01-19 06:46:48 +00001940 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001941 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla74948d2011-09-24 17:48:25 +00001942 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001943 return true;
1944 }
John McCallb5a0d312009-12-21 10:41:20 +00001945 }
1946
Douglas Gregora3b624a2010-01-19 06:46:48 +00001947 if (BaseType.isNull()) {
1948 BaseType = Context.getTypeDeclType(TyD);
1949 if (SS.isSet()) {
1950 NestedNameSpecifier *Qualifier =
1951 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001952
Douglas Gregora3b624a2010-01-19 06:46:48 +00001953 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001954 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001955 }
John McCallb5a0d312009-12-21 10:41:20 +00001956 }
1957 }
Mike Stump11289f42009-09-09 15:08:12 +00001958
John McCallbcd03502009-12-07 02:54:59 +00001959 if (!TInfo)
1960 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001961
Sebastian Redla74948d2011-09-24 17:48:25 +00001962 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001963}
1964
Chandler Carruth599deef2011-09-03 01:14:15 +00001965/// Checks a member initializer expression for cases where reference (or
1966/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001967static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1968 Expr *Init,
1969 SourceLocation IdLoc) {
1970 QualType MemberTy = Member->getType();
1971
1972 // We only handle pointers and references currently.
1973 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1974 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1975 return;
1976
1977 const bool IsPointer = MemberTy->isPointerType();
1978 if (IsPointer) {
1979 if (const UnaryOperator *Op
1980 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1981 // The only case we're worried about with pointers requires taking the
1982 // address.
1983 if (Op->getOpcode() != UO_AddrOf)
1984 return;
1985
1986 Init = Op->getSubExpr();
1987 } else {
1988 // We only handle address-of expression initializers for pointers.
1989 return;
1990 }
1991 }
1992
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001993 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1994 // Taking the address of a temporary will be diagnosed as a hard error.
1995 if (IsPointer)
1996 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001997
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001998 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1999 << Member << Init->getSourceRange();
2000 } else if (const DeclRefExpr *DRE
2001 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2002 // We only warn when referring to a non-reference parameter declaration.
2003 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2004 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002005 return;
2006
2007 S.Diag(Init->getExprLoc(),
2008 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2009 : diag::warn_bind_ref_member_to_parameter)
2010 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002011 } else {
2012 // Other initializers are fine.
2013 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002014 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002015
2016 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2017 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002018}
2019
John McCalle22a04a2009-11-04 23:02:40 +00002020/// Checks an initializer expression for use of uninitialized fields, such as
2021/// containing the field that is being initialized. Returns true if there is an
2022/// uninitialized field was used an updates the SourceLocation parameter; false
2023/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002024static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00002025 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002026 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00002027 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2028
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002029 if (isa<CallExpr>(S)) {
2030 // Do not descend into function calls or constructors, as the use
2031 // of an uninitialized field may be valid. One would have to inspect
2032 // the contents of the function/ctor to determine if it is safe or not.
2033 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2034 // may be safe, depending on what the function/ctor does.
2035 return false;
2036 }
2037 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2038 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002039
2040 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2041 // The member expression points to a static data member.
2042 assert(VD->isStaticDataMember() &&
2043 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00002044 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002045 return false;
2046 }
2047
2048 if (isa<EnumConstantDecl>(RhsField)) {
2049 // The member expression points to an enum.
2050 return false;
2051 }
2052
John McCalle22a04a2009-11-04 23:02:40 +00002053 if (RhsField == LhsField) {
2054 // Initializing a field with itself. Throw a warning.
2055 // But wait; there are exceptions!
2056 // Exception #1: The field may not belong to this record.
2057 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002058 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00002059 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2060 // Even though the field matches, it does not belong to this record.
2061 return false;
2062 }
2063 // None of the exceptions triggered; return true to indicate an
2064 // uninitialized field was used.
2065 *L = ME->getMemberLoc();
2066 return true;
2067 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002068 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00002069 // sizeof/alignof doesn't reference contents, do not warn.
2070 return false;
2071 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2072 // address-of doesn't reference contents (the pointer may be dereferenced
2073 // in the same expression but it would be rare; and weird).
2074 if (UOE->getOpcode() == UO_AddrOf)
2075 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002076 }
John McCall8322c3a2011-02-13 04:07:26 +00002077 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002078 if (!*it) {
2079 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00002080 continue;
2081 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002082 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2083 return true;
John McCalle22a04a2009-11-04 23:02:40 +00002084 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002085 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002086}
2087
John McCallfaf5fb42010-08-26 23:41:50 +00002088MemInitResult
Sebastian Redla74948d2011-09-24 17:48:25 +00002089Sema::BuildMemberInitializer(ValueDecl *Member,
2090 const MultiInitializer &Args,
2091 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002092 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2093 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2094 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002095 "Member must be a FieldDecl or IndirectFieldDecl");
2096
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002097 if (Args.DiagnoseUnexpandedParameterPack(*this))
2098 return true;
2099
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002100 if (Member->isInvalidDecl())
2101 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002102
John McCalle22a04a2009-11-04 23:02:40 +00002103 // Diagnose value-uses of fields to initialize themselves, e.g.
2104 // foo(foo)
2105 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002106 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla74948d2011-09-24 17:48:25 +00002107 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2108 I != E; ++I) {
John McCalle22a04a2009-11-04 23:02:40 +00002109 SourceLocation L;
Sebastian Redla74948d2011-09-24 17:48:25 +00002110 Expr *Arg = *I;
2111 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2112 Arg = DIE->getInit();
2113 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00002114 // FIXME: Return true in the case when other fields are used before being
2115 // uninitialized. For example, let this field be the i'th field. When
2116 // initializing the i'th field, throw a warning if any of the >= i'th
2117 // fields are used, as they are not yet initialized.
2118 // Right now we are only handling the case where the i'th field uses
2119 // itself in its initializer.
2120 Diag(L, diag::warn_field_is_uninit);
2121 }
2122 }
2123
Sebastian Redla74948d2011-09-24 17:48:25 +00002124 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002125
Chandler Carruthd44c3102010-12-06 09:23:57 +00002126 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00002127 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002128 // Can't check initialization for a member of dependent type or when
2129 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002130 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002131
John McCall31168b02011-06-15 23:02:42 +00002132 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002133 } else {
2134 // Initialize the member.
2135 InitializedEntity MemberEntity =
2136 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2137 : InitializedEntity::InitializeMember(IndirectMember, 0);
2138 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002139 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2140 Args.getEndLoc());
John McCallacf0ee52010-10-08 02:01:28 +00002141
Sebastian Redla74948d2011-09-24 17:48:25 +00002142 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002143 if (MemberInit.isInvalid())
2144 return true;
2145
Sebastian Redla74948d2011-09-24 17:48:25 +00002146 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002147
2148 // C++0x [class.base.init]p7:
2149 // The initialization of each base and member constitutes a
2150 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002151 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002152 if (MemberInit.isInvalid())
2153 return true;
2154
2155 // If we are in a dependent context, template instantiation will
2156 // perform this type-checking again. Just save the arguments that we
2157 // received in a ParenListExpr.
2158 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2159 // of the information that we have about the member
2160 // initializer. However, deconstructing the ASTs is a dicey process,
2161 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00002162 if (CurContext->isDependentContext()) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002163 Init = Args.CreateInitExpr(Context,
2164 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00002165 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002166 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00002167 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2168 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002169 }
2170
Chandler Carruthd44c3102010-12-06 09:23:57 +00002171 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002172 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002173 IdLoc, Args.getStartLoc(),
2174 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002175 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00002176 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002177 IdLoc, Args.getStartLoc(),
2178 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002179 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002180}
2181
John McCallfaf5fb42010-08-26 23:41:50 +00002182MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002183Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002184 const MultiInitializer &Args,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002185 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002186 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002187 if (!LangOpts.CPlusPlus0x)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002188 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002189 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002190 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002191
Alexis Huntc5575cc2011-02-26 19:13:13 +00002192 // Initialize the object.
2193 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2194 QualType(ClassDecl->getTypeForDecl(), 0));
2195 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002196 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2197 Args.getEndLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002198
Sebastian Redla74948d2011-09-24 17:48:25 +00002199 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002200 if (DelegationInit.isInvalid())
2201 return true;
2202
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002203 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2204 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002205
Sebastian Redla74948d2011-09-24 17:48:25 +00002206 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002207
2208 // C++0x [class.base.init]p7:
2209 // The initialization of each base and member constitutes a
2210 // full-expression.
2211 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2212 if (DelegationInit.isInvalid())
2213 return true;
2214
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002215 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002216 DelegationInit.takeAs<Expr>(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002217 Args.getEndLoc());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002218}
2219
2220MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002221Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002222 const MultiInitializer &Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002223 CXXRecordDecl *ClassDecl,
2224 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002225 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002226
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002227 SourceLocation BaseLoc
2228 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002229
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002230 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2231 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2232 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2233
2234 // C++ [class.base.init]p2:
2235 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002236 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002237 // of that class, the mem-initializer is ill-formed. A
2238 // mem-initializer-list can initialize a base class using any
2239 // name that denotes that base class type.
2240 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2241
Douglas Gregor44e7df62011-01-04 00:32:56 +00002242 if (EllipsisLoc.isValid()) {
2243 // This is a pack expansion.
2244 if (!BaseType->containsUnexpandedParameterPack()) {
2245 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla74948d2011-09-24 17:48:25 +00002246 << SourceRange(BaseLoc, Args.getEndLoc());
2247
Douglas Gregor44e7df62011-01-04 00:32:56 +00002248 EllipsisLoc = SourceLocation();
2249 }
2250 } else {
2251 // Check for any unexpanded parameter packs.
2252 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2253 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002254
2255 if (Args.DiagnoseUnexpandedParameterPack(*this))
2256 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002257 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002258
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002259 // Check for direct and virtual base classes.
2260 const CXXBaseSpecifier *DirectBaseSpec = 0;
2261 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2262 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002263 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2264 BaseType))
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002265 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002266
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002267 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2268 VirtualBaseSpec);
2269
2270 // C++ [base.class.init]p2:
2271 // Unless the mem-initializer-id names a nonstatic data member of the
2272 // constructor's class or a direct or virtual base of that class, the
2273 // mem-initializer is ill-formed.
2274 if (!DirectBaseSpec && !VirtualBaseSpec) {
2275 // If the class has any dependent bases, then it's possible that
2276 // one of those types will resolve to the same type as
2277 // BaseType. Therefore, just treat this as a dependent base
2278 // class initialization. FIXME: Should we try to check the
2279 // initialization anyway? It seems odd.
2280 if (ClassDecl->hasAnyDependentBases())
2281 Dependent = true;
2282 else
2283 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2284 << BaseType << Context.getTypeDeclType(ClassDecl)
2285 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2286 }
2287 }
2288
2289 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002290 // Can't check initialization for a base of dependent type or when
2291 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002292 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002293
John McCall31168b02011-06-15 23:02:42 +00002294 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002295
Sebastian Redla74948d2011-09-24 17:48:25 +00002296 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2297 /*IsVirtual=*/false,
2298 Args.getStartLoc(), BaseInit,
2299 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002300 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002301
2302 // C++ [base.class.init]p2:
2303 // If a mem-initializer-id is ambiguous because it designates both
2304 // a direct non-virtual base class and an inherited virtual base
2305 // class, the mem-initializer is ill-formed.
2306 if (DirectBaseSpec && VirtualBaseSpec)
2307 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002308 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002309
2310 CXXBaseSpecifier *BaseSpec
2311 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2312 if (!BaseSpec)
2313 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2314
2315 // Initialize the base.
2316 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00002317 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002318 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002319 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2320 Args.getEndLoc());
2321
2322 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002323 if (BaseInit.isInvalid())
2324 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002325
Sebastian Redla74948d2011-09-24 17:48:25 +00002326 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2327
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002328 // C++0x [class.base.init]p7:
2329 // The initialization of each base and member constitutes a
2330 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002331 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002332 if (BaseInit.isInvalid())
2333 return true;
2334
2335 // If we are in a dependent context, template instantiation will
2336 // perform this type-checking again. Just save the arguments that we
2337 // received in a ParenListExpr.
2338 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2339 // of the information that we have about the base
2340 // initializer. However, deconstructing the ASTs is a dicey process,
2341 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002342 if (CurContext->isDependentContext())
2343 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002344
Alexis Hunt1d792652011-01-08 20:30:50 +00002345 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002346 BaseSpec->isVirtual(),
2347 Args.getStartLoc(),
2348 BaseInit.takeAs<Expr>(),
2349 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002350}
2351
Sebastian Redl22653ba2011-08-30 19:58:05 +00002352// Create a static_cast\<T&&>(expr).
2353static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2354 QualType ExprType = E->getType();
2355 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2356 SourceLocation ExprLoc = E->getLocStart();
2357 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2358 TargetType, ExprLoc);
2359
2360 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2361 SourceRange(ExprLoc, ExprLoc),
2362 E->getSourceRange()).take();
2363}
2364
Anders Carlsson1b00e242010-04-23 03:10:23 +00002365/// ImplicitInitializerKind - How an implicit base or member initializer should
2366/// initialize its base or member.
2367enum ImplicitInitializerKind {
2368 IIK_Default,
2369 IIK_Copy,
2370 IIK_Move
2371};
2372
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002373static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002374BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002375 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002376 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002377 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002378 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002379 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002380 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2381 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002382
John McCalldadc5752010-08-24 06:29:42 +00002383 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002384
2385 switch (ImplicitInitKind) {
2386 case IIK_Default: {
2387 InitializationKind InitKind
2388 = InitializationKind::CreateDefault(Constructor->getLocation());
2389 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2390 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002391 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002392 break;
2393 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002394
Sebastian Redl22653ba2011-08-30 19:58:05 +00002395 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002396 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002397 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002398 ParmVarDecl *Param = Constructor->getParamDecl(0);
2399 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00002400
Anders Carlsson1b00e242010-04-23 03:10:23 +00002401 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002402 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2403 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002404 Constructor->getLocation(), ParamType,
2405 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002406
Eli Friedmanfa0df832012-02-02 03:46:19 +00002407 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2408
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002409 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002410 QualType ArgTy =
2411 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2412 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002413
Sebastian Redl22653ba2011-08-30 19:58:05 +00002414 if (Moving) {
2415 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2416 }
2417
John McCallcf142162010-08-07 06:22:56 +00002418 CXXCastPath BasePath;
2419 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002420 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2421 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002422 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002423 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002424
Anders Carlsson1b00e242010-04-23 03:10:23 +00002425 InitializationKind InitKind
2426 = InitializationKind::CreateDirect(Constructor->getLocation(),
2427 SourceLocation(), SourceLocation());
2428 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2429 &CopyCtorArg, 1);
2430 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002431 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002432 break;
2433 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002434 }
John McCallb268a282010-08-23 23:25:46 +00002435
Douglas Gregora40433a2010-12-07 00:41:46 +00002436 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002437 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002438 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002439
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002440 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002441 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002442 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2443 SourceLocation()),
2444 BaseSpec->isVirtual(),
2445 SourceLocation(),
2446 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002447 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002448 SourceLocation());
2449
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002450 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002451}
2452
Sebastian Redl22653ba2011-08-30 19:58:05 +00002453static bool RefersToRValueRef(Expr *MemRef) {
2454 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2455 return Referenced->getType()->isRValueReferenceType();
2456}
2457
Anders Carlsson3c1db572010-04-23 02:15:47 +00002458static bool
2459BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002460 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002461 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002462 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002463 if (Field->isInvalidDecl())
2464 return true;
2465
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002466 SourceLocation Loc = Constructor->getLocation();
2467
Sebastian Redl22653ba2011-08-30 19:58:05 +00002468 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2469 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002470 ParmVarDecl *Param = Constructor->getParamDecl(0);
2471 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002472
2473 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00002474 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2475 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002476
Anders Carlsson423f5d82010-04-23 16:04:08 +00002477 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002478 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2479 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002480 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002481
Eli Friedmanfa0df832012-02-02 03:46:19 +00002482 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2483
Sebastian Redl22653ba2011-08-30 19:58:05 +00002484 if (Moving) {
2485 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2486 }
2487
Douglas Gregor94f9a482010-05-05 05:51:00 +00002488 // Build a reference to this field within the parameter.
2489 CXXScopeSpec SS;
2490 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2491 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002492 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2493 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002494 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002495 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002496 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002497 ParamType, Loc,
2498 /*IsArrow=*/false,
2499 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002500 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002501 /*FirstQualifierInScope=*/0,
2502 MemberLookup,
2503 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002504 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002505 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002506
2507 // C++11 [class.copy]p15:
2508 // - if a member m has rvalue reference type T&&, it is direct-initialized
2509 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002510 if (RefersToRValueRef(CtorArg.get())) {
2511 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002512 }
2513
Douglas Gregor94f9a482010-05-05 05:51:00 +00002514 // When the field we are copying is an array, create index variables for
2515 // each dimension of the array. We use these index variables to subscript
2516 // the source array, and other clients (e.g., CodeGen) will perform the
2517 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002518 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002519 QualType BaseType = Field->getType();
2520 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002521 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002522 while (const ConstantArrayType *Array
2523 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002524 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002525 // Create the iteration variable for this array index.
2526 IdentifierInfo *IterationVarName = 0;
2527 {
2528 llvm::SmallString<8> Str;
2529 llvm::raw_svector_ostream OS(Str);
2530 OS << "__i" << IndexVariables.size();
2531 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2532 }
2533 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002534 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002535 IterationVarName, SizeType,
2536 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002537 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002538 IndexVariables.push_back(IterationVar);
2539
2540 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002541 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00002542 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002543 assert(!IterationVarRef.isInvalid() &&
2544 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00002545 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2546 assert(!IterationVarRef.isInvalid() &&
2547 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002548
Douglas Gregor94f9a482010-05-05 05:51:00 +00002549 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002550 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002551 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002552 Loc);
2553 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002554 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002555
Douglas Gregor94f9a482010-05-05 05:51:00 +00002556 BaseType = Array->getElementType();
2557 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002558
2559 // The array subscript expression is an lvalue, which is wrong for moving.
2560 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002561 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002562
Douglas Gregor94f9a482010-05-05 05:51:00 +00002563 // Construct the entity that we will be initializing. For an array, this
2564 // will be first element in the array, which may require several levels
2565 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002566 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002567 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002568 if (Indirect)
2569 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2570 else
2571 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002572 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2573 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2574 0,
2575 Entities.back()));
2576
2577 // Direct-initialize to use the copy constructor.
2578 InitializationKind InitKind =
2579 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2580
Sebastian Redle9c4e842011-09-04 18:14:28 +00002581 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002582 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002583 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002584
John McCalldadc5752010-08-24 06:29:42 +00002585 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002586 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002587 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002588 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002589 if (MemberInit.isInvalid())
2590 return true;
2591
Douglas Gregor493627b2011-08-10 15:22:55 +00002592 if (Indirect) {
2593 assert(IndexVariables.size() == 0 &&
2594 "Indirect field improperly initialized");
2595 CXXMemberInit
2596 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2597 Loc, Loc,
2598 MemberInit.takeAs<Expr>(),
2599 Loc);
2600 } else
2601 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2602 Loc, MemberInit.takeAs<Expr>(),
2603 Loc,
2604 IndexVariables.data(),
2605 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002606 return false;
2607 }
2608
Anders Carlsson423f5d82010-04-23 16:04:08 +00002609 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2610
Anders Carlsson3c1db572010-04-23 02:15:47 +00002611 QualType FieldBaseElementType =
2612 SemaRef.Context.getBaseElementType(Field->getType());
2613
Anders Carlsson3c1db572010-04-23 02:15:47 +00002614 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002615 InitializedEntity InitEntity
2616 = Indirect? InitializedEntity::InitializeMember(Indirect)
2617 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002618 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002619 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002620
2621 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002622 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002623 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002624
Douglas Gregora40433a2010-12-07 00:41:46 +00002625 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002626 if (MemberInit.isInvalid())
2627 return true;
2628
Douglas Gregor493627b2011-08-10 15:22:55 +00002629 if (Indirect)
2630 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2631 Indirect, Loc,
2632 Loc,
2633 MemberInit.get(),
2634 Loc);
2635 else
2636 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2637 Field, Loc, Loc,
2638 MemberInit.get(),
2639 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002640 return false;
2641 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002642
Alexis Hunt8b455182011-05-17 00:19:05 +00002643 if (!Field->getParent()->isUnion()) {
2644 if (FieldBaseElementType->isReferenceType()) {
2645 SemaRef.Diag(Constructor->getLocation(),
2646 diag::err_uninitialized_member_in_ctor)
2647 << (int)Constructor->isImplicit()
2648 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2649 << 0 << Field->getDeclName();
2650 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2651 return true;
2652 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002653
Alexis Hunt8b455182011-05-17 00:19:05 +00002654 if (FieldBaseElementType.isConstQualified()) {
2655 SemaRef.Diag(Constructor->getLocation(),
2656 diag::err_uninitialized_member_in_ctor)
2657 << (int)Constructor->isImplicit()
2658 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2659 << 1 << Field->getDeclName();
2660 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2661 return true;
2662 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002663 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002664
John McCall31168b02011-06-15 23:02:42 +00002665 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2666 FieldBaseElementType->isObjCRetainableType() &&
2667 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2668 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2669 // Instant objects:
2670 // Default-initialize Objective-C pointers to NULL.
2671 CXXMemberInit
2672 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2673 Loc, Loc,
2674 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2675 Loc);
2676 return false;
2677 }
2678
Anders Carlsson3c1db572010-04-23 02:15:47 +00002679 // Nothing to initialize.
2680 CXXMemberInit = 0;
2681 return false;
2682}
John McCallbc83b3f2010-05-20 23:23:51 +00002683
2684namespace {
2685struct BaseAndFieldInfo {
2686 Sema &S;
2687 CXXConstructorDecl *Ctor;
2688 bool AnyErrorsInInits;
2689 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002690 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002691 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002692
2693 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2694 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002695 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2696 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002697 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002698 else if (Generated && Ctor->isMoveConstructor())
2699 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002700 else
2701 IIK = IIK_Default;
2702 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00002703
2704 bool isImplicitCopyOrMove() const {
2705 switch (IIK) {
2706 case IIK_Copy:
2707 case IIK_Move:
2708 return true;
2709
2710 case IIK_Default:
2711 return false;
2712 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002713
2714 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00002715 }
John McCallbc83b3f2010-05-20 23:23:51 +00002716};
2717}
2718
Richard Smithc94ec842011-09-19 13:34:43 +00002719/// \brief Determine whether the given indirect field declaration is somewhere
2720/// within an anonymous union.
2721static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2722 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2723 CEnd = F->chain_end();
2724 C != CEnd; ++C)
2725 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2726 if (Record->isUnion())
2727 return true;
2728
2729 return false;
2730}
2731
Douglas Gregor10f939c2011-11-02 23:04:16 +00002732/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2733/// array type.
2734static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2735 if (T->isIncompleteArrayType())
2736 return true;
2737
2738 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2739 if (!ArrayT->getSize())
2740 return true;
2741
2742 T = ArrayT->getElementType();
2743 }
2744
2745 return false;
2746}
2747
Richard Smith938f40b2011-06-11 17:19:42 +00002748static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002749 FieldDecl *Field,
2750 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002751
Chandler Carruth139e9622010-06-30 02:59:29 +00002752 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002753 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002754 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002755 return false;
2756 }
2757
Richard Smith938f40b2011-06-11 17:19:42 +00002758 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2759 // has a brace-or-equal-initializer, the entity is initialized as specified
2760 // in [dcl.init].
Douglas Gregor7db3e952011-11-28 20:03:15 +00002761 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002762 CXXCtorInitializer *Init;
2763 if (Indirect)
2764 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2765 SourceLocation(),
2766 SourceLocation(), 0,
2767 SourceLocation());
2768 else
2769 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2770 SourceLocation(),
2771 SourceLocation(), 0,
2772 SourceLocation());
2773 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002774 return false;
2775 }
2776
Richard Smith12d5ed82011-09-18 11:14:50 +00002777 // Don't build an implicit initializer for union members if none was
2778 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002779 if (Field->getParent()->isUnion() ||
2780 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002781 return false;
2782
Douglas Gregor10f939c2011-11-02 23:04:16 +00002783 // Don't initialize incomplete or zero-length arrays.
2784 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2785 return false;
2786
John McCallbc83b3f2010-05-20 23:23:51 +00002787 // Don't try to build an implicit initializer if there were semantic
2788 // errors in any of the initializers (and therefore we might be
2789 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002790 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002791 return false;
2792
Alexis Hunt1d792652011-01-08 20:30:50 +00002793 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002794 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2795 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002796 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002797
Francois Pichetd583da02010-12-04 09:14:42 +00002798 if (Init)
2799 Info.AllToInit.push_back(Init);
2800
John McCallbc83b3f2010-05-20 23:23:51 +00002801 return false;
2802}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002803
2804bool
2805Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2806 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002807 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002808 Constructor->setNumCtorInitializers(1);
2809 CXXCtorInitializer **initializer =
2810 new (Context) CXXCtorInitializer*[1];
2811 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2812 Constructor->setCtorInitializers(initializer);
2813
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002814 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002815 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002816 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2817 }
2818
Alexis Hunte2622992011-05-05 00:05:47 +00002819 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002820
Alexis Hunt61bc1732011-05-01 07:04:31 +00002821 return false;
2822}
Douglas Gregor493627b2011-08-10 15:22:55 +00002823
John McCall1b1a1db2011-06-17 00:18:42 +00002824bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2825 CXXCtorInitializer **Initializers,
2826 unsigned NumInitializers,
2827 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002828 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002829 // Just store the initializers as written, they will be checked during
2830 // instantiation.
2831 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002832 Constructor->setNumCtorInitializers(NumInitializers);
2833 CXXCtorInitializer **baseOrMemberInitializers =
2834 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002835 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002836 NumInitializers * sizeof(CXXCtorInitializer*));
2837 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002838 }
2839
2840 return false;
2841 }
2842
John McCallbc83b3f2010-05-20 23:23:51 +00002843 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002844
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002845 // We need to build the initializer AST according to order of construction
2846 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002847 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002848 if (!ClassDecl)
2849 return true;
2850
Eli Friedman9cf6b592009-11-09 19:20:36 +00002851 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002852
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002853 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002854 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002855
2856 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002857 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002858 else
Francois Pichetd583da02010-12-04 09:14:42 +00002859 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002860 }
2861
Anders Carlsson43c64af2010-04-21 19:52:01 +00002862 // Keep track of the direct virtual bases.
2863 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2864 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2865 E = ClassDecl->bases_end(); I != E; ++I) {
2866 if (I->isVirtual())
2867 DirectVBases.insert(I);
2868 }
2869
Anders Carlssondb0a9652010-04-02 06:26:44 +00002870 // Push virtual bases before others.
2871 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2872 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2873
Alexis Hunt1d792652011-01-08 20:30:50 +00002874 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002875 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2876 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002877 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002878 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002879 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002880 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002881 VBase, IsInheritedVirtualBase,
2882 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002883 HadError = true;
2884 continue;
2885 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002886
John McCallbc83b3f2010-05-20 23:23:51 +00002887 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002888 }
2889 }
Mike Stump11289f42009-09-09 15:08:12 +00002890
John McCallbc83b3f2010-05-20 23:23:51 +00002891 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002892 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2893 E = ClassDecl->bases_end(); Base != E; ++Base) {
2894 // Virtuals are in the virtual base list and already constructed.
2895 if (Base->isVirtual())
2896 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002897
Alexis Hunt1d792652011-01-08 20:30:50 +00002898 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002899 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2900 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002901 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002902 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002903 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002904 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002905 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002906 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002907 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002908 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002909
John McCallbc83b3f2010-05-20 23:23:51 +00002910 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002911 }
2912 }
Mike Stump11289f42009-09-09 15:08:12 +00002913
John McCallbc83b3f2010-05-20 23:23:51 +00002914 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002915 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2916 MemEnd = ClassDecl->decls_end();
2917 Mem != MemEnd; ++Mem) {
2918 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00002919 // C++ [class.bit]p2:
2920 // A declaration for a bit-field that omits the identifier declares an
2921 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2922 // initialized.
2923 if (F->isUnnamedBitfield())
2924 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002925
Sebastian Redl22653ba2011-08-30 19:58:05 +00002926 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002927 // handle anonymous struct/union fields based on their individual
2928 // indirect fields.
2929 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2930 continue;
2931
2932 if (CollectFieldInitializer(*this, Info, F))
2933 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002934 continue;
2935 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002936
2937 // Beyond this point, we only consider default initialization.
2938 if (Info.IIK != IIK_Default)
2939 continue;
2940
2941 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2942 if (F->getType()->isIncompleteArrayType()) {
2943 assert(ClassDecl->hasFlexibleArrayMember() &&
2944 "Incomplete array type is not valid");
2945 continue;
2946 }
2947
Douglas Gregor493627b2011-08-10 15:22:55 +00002948 // Initialize each field of an anonymous struct individually.
2949 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2950 HadError = true;
2951
2952 continue;
2953 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
John McCallbc83b3f2010-05-20 23:23:51 +00002956 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002957 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002958 Constructor->setNumCtorInitializers(NumInitializers);
2959 CXXCtorInitializer **baseOrMemberInitializers =
2960 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002961 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002962 NumInitializers * sizeof(CXXCtorInitializer*));
2963 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002964
John McCalla6309952010-03-16 21:39:52 +00002965 // Constructors implicitly reference the base and member
2966 // destructors.
2967 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2968 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002969 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002970
2971 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002972}
2973
Eli Friedman952c15d2009-07-21 19:28:10 +00002974static void *GetKeyForTopLevelField(FieldDecl *Field) {
2975 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002976 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002977 if (RT->getDecl()->isAnonymousStructOrUnion())
2978 return static_cast<void *>(RT->getDecl());
2979 }
2980 return static_cast<void *>(Field);
2981}
2982
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002983static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002984 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002985}
2986
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002987static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002988 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002989 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002990 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002991
Eli Friedman952c15d2009-07-21 19:28:10 +00002992 // For fields injected into the class via declaration of an anonymous union,
2993 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002994 FieldDecl *Field = Member->getAnyMember();
2995
John McCall23eebd92010-04-10 09:28:51 +00002996 // If the field is a member of an anonymous struct or union, our key
2997 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002998 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002999 if (RD->isAnonymousStructOrUnion()) {
3000 while (true) {
3001 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3002 if (Parent->isAnonymousStructOrUnion())
3003 RD = Parent;
3004 else
3005 break;
3006 }
3007
Anders Carlsson83ac3122010-03-30 16:19:37 +00003008 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00003009 }
Mike Stump11289f42009-09-09 15:08:12 +00003010
Anders Carlssona942dcd2010-03-30 15:39:27 +00003011 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003012}
3013
Anders Carlssone857b292010-04-02 03:37:03 +00003014static void
3015DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003016 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00003017 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00003018 unsigned NumInits) {
3019 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003020 return;
Mike Stump11289f42009-09-09 15:08:12 +00003021
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003022 // Don't check initializers order unless the warning is enabled at the
3023 // location of at least one initializer.
3024 bool ShouldCheckOrder = false;
3025 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003026 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003027 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3028 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003029 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003030 ShouldCheckOrder = true;
3031 break;
3032 }
3033 }
3034 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003035 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003036
John McCallbb7b6582010-04-10 07:37:23 +00003037 // Build the list of bases and members in the order that they'll
3038 // actually be initialized. The explicit initializers should be in
3039 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003040 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003041
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003042 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3043
John McCallbb7b6582010-04-10 07:37:23 +00003044 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003045 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003046 ClassDecl->vbases_begin(),
3047 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003048 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003049
John McCallbb7b6582010-04-10 07:37:23 +00003050 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003051 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003052 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003053 if (Base->isVirtual())
3054 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003055 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003056 }
Mike Stump11289f42009-09-09 15:08:12 +00003057
John McCallbb7b6582010-04-10 07:37:23 +00003058 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003059 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003060 E = ClassDecl->field_end(); Field != E; ++Field) {
3061 if (Field->isUnnamedBitfield())
3062 continue;
3063
John McCallbb7b6582010-04-10 07:37:23 +00003064 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregor556e5862011-10-10 17:22:13 +00003065 }
3066
John McCallbb7b6582010-04-10 07:37:23 +00003067 unsigned NumIdealInits = IdealInitKeys.size();
3068 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003069
Alexis Hunt1d792652011-01-08 20:30:50 +00003070 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00003071 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003072 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00003073 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003074
3075 // Scan forward to try to find this initializer in the idealized
3076 // initializers list.
3077 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3078 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003079 break;
John McCallbb7b6582010-04-10 07:37:23 +00003080
3081 // If we didn't find this initializer, it must be because we
3082 // scanned past it on a previous iteration. That can only
3083 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003084 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003085 Sema::SemaDiagnosticBuilder D =
3086 SemaRef.Diag(PrevInit->getSourceLocation(),
3087 diag::warn_initializer_out_of_order);
3088
Francois Pichetd583da02010-12-04 09:14:42 +00003089 if (PrevInit->isAnyMemberInitializer())
3090 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003091 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003092 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003093
Francois Pichetd583da02010-12-04 09:14:42 +00003094 if (Init->isAnyMemberInitializer())
3095 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003096 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003097 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003098
3099 // Move back to the initializer's location in the ideal list.
3100 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3101 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003102 break;
John McCallbb7b6582010-04-10 07:37:23 +00003103
3104 assert(IdealIndex != NumIdealInits &&
3105 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003106 }
John McCallbb7b6582010-04-10 07:37:23 +00003107
3108 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003109 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003110}
3111
John McCall23eebd92010-04-10 09:28:51 +00003112namespace {
3113bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003114 CXXCtorInitializer *Init,
3115 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003116 if (!PrevInit) {
3117 PrevInit = Init;
3118 return false;
3119 }
3120
3121 if (FieldDecl *Field = Init->getMember())
3122 S.Diag(Init->getSourceLocation(),
3123 diag::err_multiple_mem_initialization)
3124 << Field->getDeclName()
3125 << Init->getSourceRange();
3126 else {
John McCall424cec92011-01-19 06:33:43 +00003127 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003128 assert(BaseClass && "neither field nor base");
3129 S.Diag(Init->getSourceLocation(),
3130 diag::err_multiple_base_initialization)
3131 << QualType(BaseClass, 0)
3132 << Init->getSourceRange();
3133 }
3134 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3135 << 0 << PrevInit->getSourceRange();
3136
3137 return true;
3138}
3139
Alexis Hunt1d792652011-01-08 20:30:50 +00003140typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003141typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3142
3143bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003144 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003145 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003146 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003147 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003148 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003149
3150 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003151 if (Parent->isUnion()) {
3152 UnionEntry &En = Unions[Parent];
3153 if (En.first && En.first != Child) {
3154 S.Diag(Init->getSourceLocation(),
3155 diag::err_multiple_mem_union_initialization)
3156 << Field->getDeclName()
3157 << Init->getSourceRange();
3158 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3159 << 0 << En.second->getSourceRange();
3160 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003161 }
3162 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003163 En.first = Child;
3164 En.second = Init;
3165 }
David Blaikie0f65d592011-11-17 06:01:57 +00003166 if (!Parent->isAnonymousStructOrUnion())
3167 return false;
John McCall23eebd92010-04-10 09:28:51 +00003168 }
3169
3170 Child = Parent;
3171 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003172 }
John McCall23eebd92010-04-10 09:28:51 +00003173
3174 return false;
3175}
3176}
3177
Anders Carlssone857b292010-04-02 03:37:03 +00003178/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003179void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003180 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00003181 CXXCtorInitializer **meminits,
3182 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003183 bool AnyErrors) {
3184 if (!ConstructorDecl)
3185 return;
3186
3187 AdjustDeclIfTemplate(ConstructorDecl);
3188
3189 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003190 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003191
3192 if (!Constructor) {
3193 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3194 return;
3195 }
3196
Alexis Hunt1d792652011-01-08 20:30:50 +00003197 CXXCtorInitializer **MemInits =
3198 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00003199
3200 // Mapping for the duplicate initializers check.
3201 // For member initializers, this is keyed with a FieldDecl*.
3202 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003203 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003204
3205 // Mapping for the inconsistent anonymous-union initializers check.
3206 RedundantUnionMap MemberUnions;
3207
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003208 bool HadError = false;
3209 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003210 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003211
Abramo Bagnara341d7832010-05-26 18:09:23 +00003212 // Set the source order index.
3213 Init->setSourceOrder(i);
3214
Francois Pichetd583da02010-12-04 09:14:42 +00003215 if (Init->isAnyMemberInitializer()) {
3216 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003217 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3218 CheckRedundantUnionInit(*this, Init, MemberUnions))
3219 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003220 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003221 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3222 if (CheckRedundantInit(*this, Init, Members[Key]))
3223 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003224 } else {
3225 assert(Init->isDelegatingInitializer());
3226 // This must be the only initializer
3227 if (i != 0 || NumMemInits > 1) {
3228 Diag(MemInits[0]->getSourceLocation(),
3229 diag::err_delegating_initializer_alone)
3230 << MemInits[0]->getSourceRange();
3231 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00003232 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003233 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003234 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003235 // Return immediately as the initializer is set.
3236 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003237 }
Anders Carlssone857b292010-04-02 03:37:03 +00003238 }
3239
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003240 if (HadError)
3241 return;
3242
Anders Carlssone857b292010-04-02 03:37:03 +00003243 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003244
Alexis Hunt1d792652011-01-08 20:30:50 +00003245 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00003246}
3247
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003248void
John McCalla6309952010-03-16 21:39:52 +00003249Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3250 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003251 // Ignore dependent contexts. Also ignore unions, since their members never
3252 // have destructors implicitly called.
3253 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003254 return;
John McCall1064d7e2010-03-16 05:22:47 +00003255
3256 // FIXME: all the access-control diagnostics are positioned on the
3257 // field/base declaration. That's probably good; that said, the
3258 // user might reasonably want to know why the destructor is being
3259 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003260
Anders Carlssondee9a302009-11-17 04:44:12 +00003261 // Non-static data members.
3262 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3263 E = ClassDecl->field_end(); I != E; ++I) {
3264 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003265 if (Field->isInvalidDecl())
3266 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003267
3268 // Don't destroy incomplete or zero-length arrays.
3269 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3270 continue;
3271
Anders Carlssondee9a302009-11-17 04:44:12 +00003272 QualType FieldType = Context.getBaseElementType(Field->getType());
3273
3274 const RecordType* RT = FieldType->getAs<RecordType>();
3275 if (!RT)
3276 continue;
3277
3278 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003279 if (FieldClassDecl->isInvalidDecl())
3280 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003281 if (FieldClassDecl->hasTrivialDestructor())
3282 continue;
3283
Douglas Gregore71edda2010-07-01 22:47:18 +00003284 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003285 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003286 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003287 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003288 << Field->getDeclName()
3289 << FieldType);
3290
Eli Friedmanfa0df832012-02-02 03:46:19 +00003291 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003292 }
3293
John McCall1064d7e2010-03-16 05:22:47 +00003294 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3295
Anders Carlssondee9a302009-11-17 04:44:12 +00003296 // Bases.
3297 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3298 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003299 // Bases are always records in a well-formed non-dependent class.
3300 const RecordType *RT = Base->getType()->getAs<RecordType>();
3301
3302 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003303 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003304 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003305
John McCall1064d7e2010-03-16 05:22:47 +00003306 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003307 // If our base class is invalid, we probably can't get its dtor anyway.
3308 if (BaseClassDecl->isInvalidDecl())
3309 continue;
3310 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00003311 if (BaseClassDecl->hasTrivialDestructor())
3312 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003313
Douglas Gregore71edda2010-07-01 22:47:18 +00003314 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003315 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003316
3317 // FIXME: caret should be on the start of the class name
3318 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003319 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003320 << Base->getType()
3321 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00003322
Eli Friedmanfa0df832012-02-02 03:46:19 +00003323 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003324 }
3325
3326 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003327 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3328 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003329
3330 // Bases are always records in a well-formed non-dependent class.
3331 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3332
3333 // Ignore direct virtual bases.
3334 if (DirectVirtualBases.count(RT))
3335 continue;
3336
John McCall1064d7e2010-03-16 05:22:47 +00003337 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003338 // If our base class is invalid, we probably can't get its dtor anyway.
3339 if (BaseClassDecl->isInvalidDecl())
3340 continue;
3341 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003342 if (BaseClassDecl->hasTrivialDestructor())
3343 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003344
Douglas Gregore71edda2010-07-01 22:47:18 +00003345 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003346 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003347 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003348 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00003349 << VBase->getType());
3350
Eli Friedmanfa0df832012-02-02 03:46:19 +00003351 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003352 }
3353}
3354
John McCall48871652010-08-21 09:40:31 +00003355void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003356 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003357 return;
Mike Stump11289f42009-09-09 15:08:12 +00003358
Mike Stump11289f42009-09-09 15:08:12 +00003359 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003360 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00003361 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003362}
3363
Mike Stump11289f42009-09-09 15:08:12 +00003364bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003365 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00003366 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00003367 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00003368 else
John McCall02db245d2010-08-18 09:41:07 +00003369 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00003370}
3371
Anders Carlssoneabf7702009-08-27 00:13:57 +00003372bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003373 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003374 if (!getLangOptions().CPlusPlus)
3375 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003376
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003377 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00003378 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00003379
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003380 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003381 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003382 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003383 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003384
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003385 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00003386 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003387 }
Mike Stump11289f42009-09-09 15:08:12 +00003388
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003389 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003390 if (!RT)
3391 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003392
John McCall67da35c2010-02-04 22:26:26 +00003393 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003394
John McCall02db245d2010-08-18 09:41:07 +00003395 // We can't answer whether something is abstract until it has a
3396 // definition. If it's currently being defined, we'll walk back
3397 // over all the declarations when we have a full definition.
3398 const CXXRecordDecl *Def = RD->getDefinition();
3399 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003400 return false;
3401
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003402 if (!RD->isAbstract())
3403 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003404
Anders Carlssoneabf7702009-08-27 00:13:57 +00003405 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00003406 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003407
John McCall02db245d2010-08-18 09:41:07 +00003408 return true;
3409}
3410
3411void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3412 // Check if we've already emitted the list of pure virtual functions
3413 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003414 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003415 return;
Mike Stump11289f42009-09-09 15:08:12 +00003416
Douglas Gregor4165bd62010-03-23 23:47:56 +00003417 CXXFinalOverriderMap FinalOverriders;
3418 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003419
Anders Carlssona2f74f32010-06-03 01:00:02 +00003420 // Keep a set of seen pure methods so we won't diagnose the same method
3421 // more than once.
3422 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3423
Douglas Gregor4165bd62010-03-23 23:47:56 +00003424 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3425 MEnd = FinalOverriders.end();
3426 M != MEnd;
3427 ++M) {
3428 for (OverridingMethods::iterator SO = M->second.begin(),
3429 SOEnd = M->second.end();
3430 SO != SOEnd; ++SO) {
3431 // C++ [class.abstract]p4:
3432 // A class is abstract if it contains or inherits at least one
3433 // pure virtual function for which the final overrider is pure
3434 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregor4165bd62010-03-23 23:47:56 +00003436 //
3437 if (SO->second.size() != 1)
3438 continue;
3439
3440 if (!SO->second.front().Method->isPure())
3441 continue;
3442
Anders Carlssona2f74f32010-06-03 01:00:02 +00003443 if (!SeenPureMethods.insert(SO->second.front().Method))
3444 continue;
3445
Douglas Gregor4165bd62010-03-23 23:47:56 +00003446 Diag(SO->second.front().Method->getLocation(),
3447 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003448 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003449 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003450 }
3451
3452 if (!PureVirtualClassDiagSet)
3453 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3454 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003455}
3456
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003457namespace {
John McCall02db245d2010-08-18 09:41:07 +00003458struct AbstractUsageInfo {
3459 Sema &S;
3460 CXXRecordDecl *Record;
3461 CanQualType AbstractType;
3462 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003463
John McCall02db245d2010-08-18 09:41:07 +00003464 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3465 : S(S), Record(Record),
3466 AbstractType(S.Context.getCanonicalType(
3467 S.Context.getTypeDeclType(Record))),
3468 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003469
John McCall02db245d2010-08-18 09:41:07 +00003470 void DiagnoseAbstractType() {
3471 if (Invalid) return;
3472 S.DiagnoseAbstractType(Record);
3473 Invalid = true;
3474 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003475
John McCall02db245d2010-08-18 09:41:07 +00003476 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3477};
3478
3479struct CheckAbstractUsage {
3480 AbstractUsageInfo &Info;
3481 const NamedDecl *Ctx;
3482
3483 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3484 : Info(Info), Ctx(Ctx) {}
3485
3486 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3487 switch (TL.getTypeLocClass()) {
3488#define ABSTRACT_TYPELOC(CLASS, PARENT)
3489#define TYPELOC(CLASS, PARENT) \
3490 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3491#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003492 }
John McCall02db245d2010-08-18 09:41:07 +00003493 }
Mike Stump11289f42009-09-09 15:08:12 +00003494
John McCall02db245d2010-08-18 09:41:07 +00003495 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3496 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3497 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003498 if (!TL.getArg(I))
3499 continue;
3500
John McCall02db245d2010-08-18 09:41:07 +00003501 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3502 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003503 }
John McCall02db245d2010-08-18 09:41:07 +00003504 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003505
John McCall02db245d2010-08-18 09:41:07 +00003506 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3507 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3508 }
Mike Stump11289f42009-09-09 15:08:12 +00003509
John McCall02db245d2010-08-18 09:41:07 +00003510 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3511 // Visit the type parameters from a permissive context.
3512 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3513 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3514 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3515 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3516 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3517 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003518 }
John McCall02db245d2010-08-18 09:41:07 +00003519 }
Mike Stump11289f42009-09-09 15:08:12 +00003520
John McCall02db245d2010-08-18 09:41:07 +00003521 // Visit pointee types from a permissive context.
3522#define CheckPolymorphic(Type) \
3523 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3524 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3525 }
3526 CheckPolymorphic(PointerTypeLoc)
3527 CheckPolymorphic(ReferenceTypeLoc)
3528 CheckPolymorphic(MemberPointerTypeLoc)
3529 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00003530 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003531
John McCall02db245d2010-08-18 09:41:07 +00003532 /// Handle all the types we haven't given a more specific
3533 /// implementation for above.
3534 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3535 // Every other kind of type that we haven't called out already
3536 // that has an inner type is either (1) sugar or (2) contains that
3537 // inner type in some way as a subobject.
3538 if (TypeLoc Next = TL.getNextTypeLoc())
3539 return Visit(Next, Sel);
3540
3541 // If there's no inner type and we're in a permissive context,
3542 // don't diagnose.
3543 if (Sel == Sema::AbstractNone) return;
3544
3545 // Check whether the type matches the abstract type.
3546 QualType T = TL.getType();
3547 if (T->isArrayType()) {
3548 Sel = Sema::AbstractArrayType;
3549 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003550 }
John McCall02db245d2010-08-18 09:41:07 +00003551 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3552 if (CT != Info.AbstractType) return;
3553
3554 // It matched; do some magic.
3555 if (Sel == Sema::AbstractArrayType) {
3556 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3557 << T << TL.getSourceRange();
3558 } else {
3559 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3560 << Sel << T << TL.getSourceRange();
3561 }
3562 Info.DiagnoseAbstractType();
3563 }
3564};
3565
3566void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3567 Sema::AbstractDiagSelID Sel) {
3568 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3569}
3570
3571}
3572
3573/// Check for invalid uses of an abstract type in a method declaration.
3574static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3575 CXXMethodDecl *MD) {
3576 // No need to do the check on definitions, which require that
3577 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003578 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003579 return;
3580
3581 // For safety's sake, just ignore it if we don't have type source
3582 // information. This should never happen for non-implicit methods,
3583 // but...
3584 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3585 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3586}
3587
3588/// Check for invalid uses of an abstract type within a class definition.
3589static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3590 CXXRecordDecl *RD) {
3591 for (CXXRecordDecl::decl_iterator
3592 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3593 Decl *D = *I;
3594 if (D->isImplicit()) continue;
3595
3596 // Methods and method templates.
3597 if (isa<CXXMethodDecl>(D)) {
3598 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3599 } else if (isa<FunctionTemplateDecl>(D)) {
3600 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3601 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3602
3603 // Fields and static variables.
3604 } else if (isa<FieldDecl>(D)) {
3605 FieldDecl *FD = cast<FieldDecl>(D);
3606 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3607 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3608 } else if (isa<VarDecl>(D)) {
3609 VarDecl *VD = cast<VarDecl>(D);
3610 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3611 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3612
3613 // Nested classes and class templates.
3614 } else if (isa<CXXRecordDecl>(D)) {
3615 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3616 } else if (isa<ClassTemplateDecl>(D)) {
3617 CheckAbstractClassUsage(Info,
3618 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3619 }
3620 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003621}
3622
Douglas Gregorc99f1552009-12-03 18:33:45 +00003623/// \brief Perform semantic checks on a class definition that has been
3624/// completing, introducing implicitly-declared members, checking for
3625/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003626void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003627 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003628 return;
3629
John McCall02db245d2010-08-18 09:41:07 +00003630 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3631 AbstractUsageInfo Info(*this, Record);
3632 CheckAbstractClassUsage(Info, Record);
3633 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003634
3635 // If this is not an aggregate type and has no user-declared constructor,
3636 // complain about any non-static data members of reference or const scalar
3637 // type, since they will never get initializers.
3638 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3639 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3640 bool Complained = false;
3641 for (RecordDecl::field_iterator F = Record->field_begin(),
3642 FEnd = Record->field_end();
3643 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003644 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00003645 continue;
3646
Douglas Gregor454a5b62010-04-15 00:00:53 +00003647 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003648 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003649 if (!Complained) {
3650 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3651 << Record->getTagKind() << Record;
3652 Complained = true;
3653 }
3654
3655 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3656 << F->getType()->isReferenceType()
3657 << F->getDeclName();
3658 }
3659 }
3660 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003661
Anders Carlssone771e762011-01-25 18:08:22 +00003662 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003663 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003664
3665 if (Record->getIdentifier()) {
3666 // C++ [class.mem]p13:
3667 // If T is the name of a class, then each of the following shall have a
3668 // name different from T:
3669 // - every member of every anonymous union that is a member of class T.
3670 //
3671 // C++ [class.mem]p14:
3672 // In addition, if class T has a user-declared constructor (12.1), every
3673 // non-static data member of class T shall have a name different from T.
3674 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003675 R.first != R.second; ++R.first) {
3676 NamedDecl *D = *R.first;
3677 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3678 isa<IndirectFieldDecl>(D)) {
3679 Diag(D->getLocation(), diag::err_member_name_of_class)
3680 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003681 break;
3682 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003683 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003684 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003685
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003686 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003687 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003688 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003689 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003690 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3691 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3692 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003693
3694 // See if a method overloads virtual methods in a base
3695 /// class without overriding any.
3696 if (!Record->isDependentType()) {
3697 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3698 MEnd = Record->method_end();
3699 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003700 if (!(*M)->isStatic())
3701 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003702 }
3703 }
Sebastian Redl08905022011-02-05 19:23:19 +00003704
Richard Smitheb3c10c2011-10-01 02:31:28 +00003705 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3706 // function that is not a constructor declares that member function to be
3707 // const. [...] The class of which that function is a member shall be
3708 // a literal type.
3709 //
3710 // It's fine to diagnose constructors here too: such constructors cannot
3711 // produce a constant expression, so are ill-formed (no diagnostic required).
3712 //
3713 // If the class has virtual bases, any constexpr members will already have
3714 // been diagnosed by the checks performed on the member declaration, so
3715 // suppress this (less useful) diagnostic.
3716 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3717 !Record->isLiteral() && !Record->getNumVBases()) {
3718 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3719 MEnd = Record->method_end();
3720 M != MEnd; ++M) {
Eli Friedmanc8002422012-01-13 02:31:53 +00003721 if (M->isConstexpr() && M->isInstance()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00003722 switch (Record->getTemplateSpecializationKind()) {
3723 case TSK_ImplicitInstantiation:
3724 case TSK_ExplicitInstantiationDeclaration:
3725 case TSK_ExplicitInstantiationDefinition:
3726 // If a template instantiates to a non-literal type, but its members
3727 // instantiate to constexpr functions, the template is technically
3728 // ill-formed, but we allow it for sanity. Such members are treated as
3729 // non-constexpr.
3730 (*M)->setConstexpr(false);
3731 continue;
3732
3733 case TSK_Undeclared:
3734 case TSK_ExplicitSpecialization:
3735 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3736 PDiag(diag::err_constexpr_method_non_literal));
3737 break;
3738 }
3739
3740 // Only produce one error per class.
3741 break;
3742 }
3743 }
3744 }
3745
Sebastian Redl08905022011-02-05 19:23:19 +00003746 // Declare inherited constructors. We do this eagerly here because:
3747 // - The standard requires an eager diagnostic for conflicting inherited
3748 // constructors from different classes.
3749 // - The lazy declaration of the other implicit constructors is so as to not
3750 // waste space and performance on classes that are not meant to be
3751 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3752 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003753 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003754
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003755 if (!Record->isDependentType())
3756 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003757}
3758
3759void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003760 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3761 ME = Record->method_end();
3762 MI != ME; ++MI) {
3763 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3764 switch (getSpecialMember(*MI)) {
3765 case CXXDefaultConstructor:
3766 CheckExplicitlyDefaultedDefaultConstructor(
3767 cast<CXXConstructorDecl>(*MI));
3768 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003769
Alexis Huntf91729462011-05-12 22:46:25 +00003770 case CXXDestructor:
3771 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3772 break;
3773
3774 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003775 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3776 break;
3777
Alexis Huntf91729462011-05-12 22:46:25 +00003778 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003779 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003780 break;
3781
Alexis Hunt119c10e2011-05-25 23:16:36 +00003782 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003783 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003784 break;
3785
Sebastian Redl22653ba2011-08-30 19:58:05 +00003786 case CXXMoveAssignment:
3787 CheckExplicitlyDefaultedMoveAssignment(*MI);
3788 break;
3789
3790 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003791 llvm_unreachable("non-special member explicitly defaulted!");
3792 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003793 }
3794 }
3795
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003796}
3797
3798void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3799 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3800
3801 // Whether this was the first-declared instance of the constructor.
3802 // This affects whether we implicitly add an exception spec (and, eventually,
3803 // constexpr). It is also ill-formed to explicitly default a constructor such
3804 // that it would be deleted. (C++0x [decl.fct.def.default])
3805 bool First = CD == CD->getCanonicalDecl();
3806
Alexis Hunt913820d2011-05-13 06:10:58 +00003807 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003808 if (CD->getNumParams() != 0) {
3809 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3810 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003811 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003812 }
3813
3814 ImplicitExceptionSpecification Spec
3815 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3816 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003817 if (EPI.ExceptionSpecType == EST_Delayed) {
3818 // Exception specification depends on some deferred part of the class. We'll
3819 // try again when the class's definition has been fully processed.
3820 return;
3821 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003822 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3823 *ExceptionType = Context.getFunctionType(
3824 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3825
Richard Smithcc36f692011-12-22 02:22:31 +00003826 // C++11 [dcl.fct.def.default]p2:
3827 // An explicitly-defaulted function may be declared constexpr only if it
3828 // would have been implicitly declared as constexpr,
3829 if (CD->isConstexpr()) {
3830 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3831 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3832 << CXXDefaultConstructor;
3833 HadError = true;
3834 }
3835 }
3836 // and may have an explicit exception-specification only if it is compatible
3837 // with the exception-specification on the implicit declaration.
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003838 if (CtorType->hasExceptionSpec()) {
3839 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003840 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003841 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003842 PDiag(),
3843 ExceptionType, SourceLocation(),
3844 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003845 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003846 }
Richard Smithcc36f692011-12-22 02:22:31 +00003847 }
3848
3849 // If a function is explicitly defaulted on its first declaration,
3850 if (First) {
3851 // -- it is implicitly considered to be constexpr if the implicit
3852 // definition would be,
3853 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3854
3855 // -- it is implicitly considered to have the same
3856 // exception-specification as if it had been implicitly declared
3857 //
3858 // FIXME: a compatible, but different, explicit exception specification
3859 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003860 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003861 }
Alexis Huntb3153022011-05-12 03:51:48 +00003862
Alexis Hunt913820d2011-05-13 06:10:58 +00003863 if (HadError) {
3864 CD->setInvalidDecl();
3865 return;
3866 }
3867
Alexis Huntd6da8762011-10-10 06:18:57 +00003868 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003869 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003870 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003871 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003872 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003873 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003874 CD->setInvalidDecl();
3875 }
3876 }
3877}
3878
3879void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3880 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3881
3882 // Whether this was the first-declared instance of the constructor.
3883 bool First = CD == CD->getCanonicalDecl();
3884
3885 bool HadError = false;
3886 if (CD->getNumParams() != 1) {
3887 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3888 << CD->getSourceRange();
3889 HadError = true;
3890 }
3891
3892 ImplicitExceptionSpecification Spec(Context);
3893 bool Const;
3894 llvm::tie(Spec, Const) =
3895 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3896
3897 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3898 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3899 *ExceptionType = Context.getFunctionType(
3900 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3901
3902 // Check for parameter type matching.
3903 // This is a copy ctor so we know it's a cv-qualified reference to T.
3904 QualType ArgType = CtorType->getArgType(0);
3905 if (ArgType->getPointeeType().isVolatileQualified()) {
3906 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3907 HadError = true;
3908 }
3909 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3910 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3911 HadError = true;
3912 }
3913
Richard Smithcc36f692011-12-22 02:22:31 +00003914 // C++11 [dcl.fct.def.default]p2:
3915 // An explicitly-defaulted function may be declared constexpr only if it
3916 // would have been implicitly declared as constexpr,
3917 if (CD->isConstexpr()) {
3918 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3919 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3920 << CXXCopyConstructor;
3921 HadError = true;
3922 }
3923 }
3924 // and may have an explicit exception-specification only if it is compatible
3925 // with the exception-specification on the implicit declaration.
Alexis Hunt913820d2011-05-13 06:10:58 +00003926 if (CtorType->hasExceptionSpec()) {
3927 if (CheckEquivalentExceptionSpec(
3928 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003929 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003930 PDiag(),
3931 ExceptionType, SourceLocation(),
3932 CtorType, CD->getLocation())) {
3933 HadError = true;
3934 }
Richard Smithcc36f692011-12-22 02:22:31 +00003935 }
3936
3937 // If a function is explicitly defaulted on its first declaration,
3938 if (First) {
3939 // -- it is implicitly considered to be constexpr if the implicit
3940 // definition would be,
3941 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3942
3943 // -- it is implicitly considered to have the same
3944 // exception-specification as if it had been implicitly declared, and
3945 //
3946 // FIXME: a compatible, but different, explicit exception specification
3947 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003948 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00003949
3950 // -- [...] it shall have the same parameter type as if it had been
3951 // implicitly declared.
Alexis Hunt913820d2011-05-13 06:10:58 +00003952 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3953 }
3954
3955 if (HadError) {
3956 CD->setInvalidDecl();
3957 return;
3958 }
3959
Alexis Hunt1bc6f712011-10-11 04:55:36 +00003960 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003961 if (First) {
3962 CD->setDeletedAsWritten();
3963 } else {
3964 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003965 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003966 CD->setInvalidDecl();
3967 }
Alexis Huntb3153022011-05-12 03:51:48 +00003968 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003969}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003970
Alexis Huntc9a55732011-05-14 05:23:28 +00003971void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3972 assert(MD->isExplicitlyDefaulted());
3973
3974 // Whether this was the first-declared instance of the operator
3975 bool First = MD == MD->getCanonicalDecl();
3976
3977 bool HadError = false;
3978 if (MD->getNumParams() != 1) {
3979 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3980 << MD->getSourceRange();
3981 HadError = true;
3982 }
3983
3984 QualType ReturnType =
3985 MD->getType()->getAs<FunctionType>()->getResultType();
3986 if (!ReturnType->isLValueReferenceType() ||
3987 !Context.hasSameType(
3988 Context.getCanonicalType(ReturnType->getPointeeType()),
3989 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3990 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3991 HadError = true;
3992 }
3993
3994 ImplicitExceptionSpecification Spec(Context);
3995 bool Const;
3996 llvm::tie(Spec, Const) =
3997 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3998
3999 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4000 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4001 *ExceptionType = Context.getFunctionType(
4002 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4003
Alexis Huntc9a55732011-05-14 05:23:28 +00004004 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004005 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00004006 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004007 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00004008 } else {
4009 if (ArgType->getPointeeType().isVolatileQualified()) {
4010 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4011 HadError = true;
4012 }
4013 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4014 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4015 HadError = true;
4016 }
Alexis Huntc9a55732011-05-14 05:23:28 +00004017 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004018
Alexis Huntc9a55732011-05-14 05:23:28 +00004019 if (OperType->getTypeQuals()) {
4020 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4021 HadError = true;
4022 }
4023
4024 if (OperType->hasExceptionSpec()) {
4025 if (CheckEquivalentExceptionSpec(
4026 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004027 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00004028 PDiag(),
4029 ExceptionType, SourceLocation(),
4030 OperType, MD->getLocation())) {
4031 HadError = true;
4032 }
Richard Smithcc36f692011-12-22 02:22:31 +00004033 }
4034 if (First) {
Alexis Huntc9a55732011-05-14 05:23:28 +00004035 // 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 (ShouldDeleteCopyAssignmentOperator(MD)) {
4048 if (First) {
4049 MD->setDeletedAsWritten();
4050 } else {
4051 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004052 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00004053 MD->setInvalidDecl();
4054 }
4055 }
4056}
4057
Sebastian Redl22653ba2011-08-30 19:58:05 +00004058void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4059 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4060
4061 // Whether this was the first-declared instance of the constructor.
4062 bool First = CD == CD->getCanonicalDecl();
4063
4064 bool HadError = false;
4065 if (CD->getNumParams() != 1) {
4066 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4067 << CD->getSourceRange();
4068 HadError = true;
4069 }
4070
4071 ImplicitExceptionSpecification Spec(
4072 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4073
4074 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4075 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4076 *ExceptionType = Context.getFunctionType(
4077 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4078
4079 // Check for parameter type matching.
4080 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4081 QualType ArgType = CtorType->getArgType(0);
4082 if (ArgType->getPointeeType().isVolatileQualified()) {
4083 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4084 HadError = true;
4085 }
4086 if (ArgType->getPointeeType().isConstQualified()) {
4087 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4088 HadError = true;
4089 }
4090
Richard Smithcc36f692011-12-22 02:22:31 +00004091 // C++11 [dcl.fct.def.default]p2:
4092 // An explicitly-defaulted function may be declared constexpr only if it
4093 // would have been implicitly declared as constexpr,
4094 if (CD->isConstexpr()) {
4095 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4096 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4097 << CXXMoveConstructor;
4098 HadError = true;
4099 }
4100 }
4101 // and may have an explicit exception-specification only if it is compatible
4102 // with the exception-specification on the implicit declaration.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004103 if (CtorType->hasExceptionSpec()) {
4104 if (CheckEquivalentExceptionSpec(
4105 PDiag(diag::err_incorrect_defaulted_exception_spec)
4106 << CXXMoveConstructor,
4107 PDiag(),
4108 ExceptionType, SourceLocation(),
4109 CtorType, CD->getLocation())) {
4110 HadError = true;
4111 }
Richard Smithcc36f692011-12-22 02:22:31 +00004112 }
4113
4114 // If a function is explicitly defaulted on its first declaration,
4115 if (First) {
4116 // -- it is implicitly considered to be constexpr if the implicit
4117 // definition would be,
4118 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4119
4120 // -- it is implicitly considered to have the same
4121 // exception-specification as if it had been implicitly declared, and
4122 //
4123 // FIXME: a compatible, but different, explicit exception specification
4124 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004125 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00004126
4127 // -- [...] it shall have the same parameter type as if it had been
4128 // implicitly declared.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004129 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4130 }
4131
4132 if (HadError) {
4133 CD->setInvalidDecl();
4134 return;
4135 }
4136
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004137 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004138 if (First) {
4139 CD->setDeletedAsWritten();
4140 } else {
4141 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4142 << CXXMoveConstructor;
4143 CD->setInvalidDecl();
4144 }
4145 }
4146}
4147
4148void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4149 assert(MD->isExplicitlyDefaulted());
4150
4151 // Whether this was the first-declared instance of the operator
4152 bool First = MD == MD->getCanonicalDecl();
4153
4154 bool HadError = false;
4155 if (MD->getNumParams() != 1) {
4156 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4157 << MD->getSourceRange();
4158 HadError = true;
4159 }
4160
4161 QualType ReturnType =
4162 MD->getType()->getAs<FunctionType>()->getResultType();
4163 if (!ReturnType->isLValueReferenceType() ||
4164 !Context.hasSameType(
4165 Context.getCanonicalType(ReturnType->getPointeeType()),
4166 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4167 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4168 HadError = true;
4169 }
4170
4171 ImplicitExceptionSpecification Spec(
4172 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4173
4174 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4175 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4176 *ExceptionType = Context.getFunctionType(
4177 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4178
4179 QualType ArgType = OperType->getArgType(0);
4180 if (!ArgType->isRValueReferenceType()) {
4181 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4182 HadError = true;
4183 } else {
4184 if (ArgType->getPointeeType().isVolatileQualified()) {
4185 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4186 HadError = true;
4187 }
4188 if (ArgType->getPointeeType().isConstQualified()) {
4189 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4190 HadError = true;
4191 }
4192 }
4193
4194 if (OperType->getTypeQuals()) {
4195 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4196 HadError = true;
4197 }
4198
4199 if (OperType->hasExceptionSpec()) {
4200 if (CheckEquivalentExceptionSpec(
4201 PDiag(diag::err_incorrect_defaulted_exception_spec)
4202 << CXXMoveAssignment,
4203 PDiag(),
4204 ExceptionType, SourceLocation(),
4205 OperType, MD->getLocation())) {
4206 HadError = true;
4207 }
Richard Smithcc36f692011-12-22 02:22:31 +00004208 }
4209 if (First) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004210 // We set the declaration to have the computed exception spec here.
4211 // We duplicate the one parameter type.
4212 EPI.RefQualifier = OperType->getRefQualifier();
4213 EPI.ExtInfo = OperType->getExtInfo();
4214 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4215 }
4216
4217 if (HadError) {
4218 MD->setInvalidDecl();
4219 return;
4220 }
4221
4222 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4223 if (First) {
4224 MD->setDeletedAsWritten();
4225 } else {
4226 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4227 << CXXMoveAssignment;
4228 MD->setInvalidDecl();
4229 }
4230 }
4231}
4232
Alexis Huntf91729462011-05-12 22:46:25 +00004233void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4234 assert(DD->isExplicitlyDefaulted());
4235
4236 // Whether this was the first-declared instance of the destructor.
4237 bool First = DD == DD->getCanonicalDecl();
4238
4239 ImplicitExceptionSpecification Spec
4240 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4241 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4242 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4243 *ExceptionType = Context.getFunctionType(
4244 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4245
4246 if (DtorType->hasExceptionSpec()) {
4247 if (CheckEquivalentExceptionSpec(
4248 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004249 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00004250 PDiag(),
4251 ExceptionType, SourceLocation(),
4252 DtorType, DD->getLocation())) {
4253 DD->setInvalidDecl();
4254 return;
4255 }
Richard Smithcc36f692011-12-22 02:22:31 +00004256 }
4257 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004258 // We set the declaration to have the computed exception spec here.
4259 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00004260 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00004261 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4262 }
4263
4264 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00004265 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004266 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00004267 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00004268 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004269 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00004270 DD->setInvalidDecl();
4271 }
Alexis Huntf91729462011-05-12 22:46:25 +00004272 }
Alexis Huntf91729462011-05-12 22:46:25 +00004273}
4274
Alexis Huntd6da8762011-10-10 06:18:57 +00004275/// This function implements the following C++0x paragraphs:
4276/// - [class.ctor]/5
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004277/// - [class.copy]/11
Alexis Huntd6da8762011-10-10 06:18:57 +00004278bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4279 assert(!MD->isInvalidDecl());
4280 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00004281 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004282 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004283 return false;
4284
Alexis Huntd6da8762011-10-10 06:18:57 +00004285 bool IsUnion = RD->isUnion();
4286 bool IsConstructor = false;
4287 bool IsAssignment = false;
4288 bool IsMove = false;
4289
4290 bool ConstArg = false;
4291
4292 switch (CSM) {
4293 case CXXDefaultConstructor:
4294 IsConstructor = true;
4295 break;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004296 case CXXCopyConstructor:
4297 IsConstructor = true;
4298 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4299 break;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004300 case CXXMoveConstructor:
4301 IsConstructor = true;
4302 IsMove = true;
4303 break;
Alexis Huntd6da8762011-10-10 06:18:57 +00004304 default:
4305 llvm_unreachable("function only currently implemented for default ctors");
4306 }
4307
4308 SourceLocation Loc = MD->getLocation();
Alexis Hunte77a28f2011-05-18 03:41:58 +00004309
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004310 // Do access control from the special member function
Alexis Huntd6da8762011-10-10 06:18:57 +00004311 ContextRAII MethodContext(*this, MD);
Alexis Huntea6f0322011-05-11 22:34:38 +00004312
Alexis Huntea6f0322011-05-11 22:34:38 +00004313 bool AllConst = true;
4314
Alexis Huntea6f0322011-05-11 22:34:38 +00004315 // We do this because we should never actually use an anonymous
4316 // union's constructor.
Alexis Huntd6da8762011-10-10 06:18:57 +00004317 if (IsUnion && RD->isAnonymousStructOrUnion())
Alexis Huntea6f0322011-05-11 22:34:38 +00004318 return false;
4319
4320 // FIXME: We should put some diagnostic logic right into this function.
4321
Alexis Huntea6f0322011-05-11 22:34:38 +00004322 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4323 BE = RD->bases_end();
4324 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00004325 // We'll handle this one later
4326 if (BI->isVirtual())
4327 continue;
4328
Alexis Huntea6f0322011-05-11 22:34:38 +00004329 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4330 assert(BaseDecl && "base isn't a CXXRecordDecl");
4331
Alexis Huntd6da8762011-10-10 06:18:57 +00004332 // Unless we have an assignment operator, the base's destructor must
4333 // be accessible and not deleted.
4334 if (!IsAssignment) {
4335 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4336 if (BaseDtor->isDeleted())
4337 return true;
4338 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4339 AR_accessible)
4340 return true;
4341 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004342
Alexis Huntd6da8762011-10-10 06:18:57 +00004343 // Finding the corresponding member in the base should lead to a
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004344 // unique, accessible, non-deleted function. If we are doing
4345 // a destructor, we have already checked this case.
Alexis Huntd6da8762011-10-10 06:18:57 +00004346 if (CSM != CXXDestructor) {
4347 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004348 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004349 false);
4350 if (!SMOR->hasSuccess())
4351 return true;
4352 CXXMethodDecl *BaseMember = SMOR->getMethod();
4353 if (IsConstructor) {
4354 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4355 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4356 PDiag()) != AR_accessible)
4357 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004358
4359 // For a move operation, the corresponding operation must actually
4360 // be a move operation (and not a copy selected by overload
4361 // resolution) unless we are working on a trivially copyable class.
4362 if (IsMove && !BaseCtor->isMoveConstructor() &&
4363 !BaseDecl->isTriviallyCopyable())
4364 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004365 }
4366 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004367 }
4368
4369 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4370 BE = RD->vbases_end();
4371 BI != BE; ++BI) {
4372 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4373 assert(BaseDecl && "base isn't a CXXRecordDecl");
4374
Alexis Huntd6da8762011-10-10 06:18:57 +00004375 // Unless we have an assignment operator, the base's destructor must
4376 // be accessible and not deleted.
4377 if (!IsAssignment) {
4378 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4379 if (BaseDtor->isDeleted())
4380 return true;
4381 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4382 AR_accessible)
4383 return true;
4384 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004385
Alexis Huntd6da8762011-10-10 06:18:57 +00004386 // Finding the corresponding member in the base should lead to a
4387 // unique, accessible, non-deleted function.
4388 if (CSM != CXXDestructor) {
4389 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004390 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004391 false);
4392 if (!SMOR->hasSuccess())
4393 return true;
4394 CXXMethodDecl *BaseMember = SMOR->getMethod();
4395 if (IsConstructor) {
4396 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4397 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4398 PDiag()) != AR_accessible)
4399 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004400
4401 // For a move operation, the corresponding operation must actually
4402 // be a move operation (and not a copy selected by overload
4403 // resolution) unless we are working on a trivially copyable class.
4404 if (IsMove && !BaseCtor->isMoveConstructor() &&
4405 !BaseDecl->isTriviallyCopyable())
4406 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004407 }
4408 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004409 }
4410
4411 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4412 FE = RD->field_end();
4413 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004414 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004415 continue;
4416
Alexis Huntea6f0322011-05-11 22:34:38 +00004417 QualType FieldType = Context.getBaseElementType(FI->getType());
4418 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00004419
Alexis Huntd6da8762011-10-10 06:18:57 +00004420 // For a default constructor, all references must be initialized in-class
4421 // and, if a union, it must have a non-const member.
4422 if (CSM == CXXDefaultConstructor) {
4423 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4424 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004425
Alexis Huntd6da8762011-10-10 06:18:57 +00004426 if (IsUnion && !FieldType.isConstQualified())
4427 AllConst = false;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004428 // For a copy constructor, data members must not be of rvalue reference
4429 // type.
4430 } else if (CSM == CXXCopyConstructor) {
4431 if (FieldType->isRValueReferenceType())
4432 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004433 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004434
4435 if (FieldRecord) {
Alexis Huntd6da8762011-10-10 06:18:57 +00004436 // For a default constructor, a const member must have a user-provided
4437 // default constructor or else be explicitly initialized.
4438 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00004439 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004440 !FieldRecord->hasUserProvidedDefaultConstructor())
4441 return true;
4442
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004443 // Some additional restrictions exist on the variant members.
4444 if (!IsUnion && FieldRecord->isUnion() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004445 FieldRecord->isAnonymousStructOrUnion()) {
4446 // We're okay to reuse AllConst here since we only care about the
4447 // value otherwise if we're in a union.
4448 AllConst = true;
4449
4450 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4451 UE = FieldRecord->field_end();
4452 UI != UE; ++UI) {
4453 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4454 CXXRecordDecl *UnionFieldRecord =
4455 UnionFieldType->getAsCXXRecordDecl();
4456
4457 if (!UnionFieldType.isConstQualified())
4458 AllConst = false;
4459
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004460 if (UnionFieldRecord) {
4461 // FIXME: Checking for accessibility and validity of this
4462 // destructor is technically going beyond the
4463 // standard, but this is believed to be a defect.
4464 if (!IsAssignment) {
4465 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4466 if (FieldDtor->isDeleted())
4467 return true;
4468 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4469 AR_accessible)
4470 return true;
4471 if (!FieldDtor->isTrivial())
4472 return true;
4473 }
4474
4475 if (CSM != CXXDestructor) {
4476 SpecialMemberOverloadResult *SMOR =
4477 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004478 false, false, false);
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004479 // FIXME: Checking for accessibility and validity of this
4480 // corresponding member is technically going beyond the
4481 // standard, but this is believed to be a defect.
4482 if (!SMOR->hasSuccess())
4483 return true;
4484
4485 CXXMethodDecl *FieldMember = SMOR->getMethod();
4486 // A member of a union must have a trivial corresponding
4487 // constructor.
4488 if (!FieldMember->isTrivial())
4489 return true;
4490
4491 if (IsConstructor) {
4492 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4493 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4494 PDiag()) != AR_accessible)
4495 return true;
4496 }
4497 }
4498 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004499 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00004500
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004501 // At least one member in each anonymous union must be non-const
4502 if (CSM == CXXDefaultConstructor && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004503 return true;
4504
4505 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00004506 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00004507 continue;
4508 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00004509
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004510 // Unless we're doing assignment, the field's destructor must be
4511 // accessible and not deleted.
4512 if (!IsAssignment) {
4513 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4514 if (FieldDtor->isDeleted())
4515 return true;
4516 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4517 AR_accessible)
4518 return true;
4519 }
4520
Alexis Huntd6da8762011-10-10 06:18:57 +00004521 // Check that the corresponding member of the field is accessible,
4522 // unique, and non-deleted. We don't do this if it has an explicit
4523 // initialization when default-constructing.
4524 if (CSM != CXXDestructor &&
4525 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4526 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004527 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004528 false);
4529 if (!SMOR->hasSuccess())
Richard Smith938f40b2011-06-11 17:19:42 +00004530 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004531
4532 CXXMethodDecl *FieldMember = SMOR->getMethod();
4533 if (IsConstructor) {
4534 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4535 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4536 PDiag()) != AR_accessible)
4537 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004538
4539 // For a move operation, the corresponding operation must actually
4540 // be a move operation (and not a copy selected by overload
4541 // resolution) unless we are working on a trivially copyable class.
4542 if (IsMove && !FieldCtor->isMoveConstructor() &&
4543 !FieldRecord->isTriviallyCopyable())
4544 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004545 }
4546
4547 // We need the corresponding member of a union to be trivial so that
4548 // we can safely copy them all simultaneously.
4549 // FIXME: Note that performing the check here (where we rely on the lack
4550 // of an in-class initializer) is technically ill-formed. However, this
4551 // seems most obviously to be a bug in the standard.
4552 if (IsUnion && !FieldMember->isTrivial())
Richard Smith938f40b2011-06-11 17:19:42 +00004553 return true;
4554 }
Alexis Huntd6da8762011-10-10 06:18:57 +00004555 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4556 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4557 // We can't initialize a const member of non-class type to any value.
Alexis Hunta671bca2011-05-20 21:43:47 +00004558 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004559 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004560 }
4561
Alexis Huntd6da8762011-10-10 06:18:57 +00004562 // We can't have all const members in a union when default-constructing,
4563 // or else they're all nonsensical garbage values that can't be changed.
4564 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004565 return true;
4566
4567 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004568}
4569
Alexis Huntb2f27802011-05-14 05:23:24 +00004570bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4571 CXXRecordDecl *RD = MD->getParent();
4572 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004573 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004574 return false;
4575
Alexis Hunte77a28f2011-05-18 03:41:58 +00004576 SourceLocation Loc = MD->getLocation();
4577
Alexis Huntb2f27802011-05-14 05:23:24 +00004578 // Do access control from the constructor
4579 ContextRAII MethodContext(*this, MD);
4580
4581 bool Union = RD->isUnion();
4582
Alexis Hunt491ec602011-06-21 23:42:56 +00004583 unsigned ArgQuals =
4584 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4585 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004586
4587 // We do this because we should never actually use an anonymous
4588 // union's constructor.
4589 if (Union && RD->isAnonymousStructOrUnion())
4590 return false;
4591
Alexis Huntb2f27802011-05-14 05:23:24 +00004592 // FIXME: We should put some diagnostic logic right into this function.
4593
Sebastian Redl22653ba2011-08-30 19:58:05 +00004594 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004595 // A defaulted [copy] assignment operator for class X is defined as deleted
4596 // if X has:
4597
4598 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4599 BE = RD->bases_end();
4600 BI != BE; ++BI) {
4601 // We'll handle this one later
4602 if (BI->isVirtual())
4603 continue;
4604
4605 QualType BaseType = BI->getType();
4606 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4607 assert(BaseDecl && "base isn't a CXXRecordDecl");
4608
4609 // -- a [direct base class] B that cannot be [copied] because overload
4610 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004611 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004612 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004613 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4614 0);
4615 if (!CopyOper || CopyOper->isDeleted())
4616 return true;
4617 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004618 return true;
4619 }
4620
4621 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4622 BE = RD->vbases_end();
4623 BI != BE; ++BI) {
4624 QualType BaseType = BI->getType();
4625 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4626 assert(BaseDecl && "base isn't a CXXRecordDecl");
4627
Alexis Huntb2f27802011-05-14 05:23:24 +00004628 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004629 // resolution, as applied to B's [copy] assignment operator, results in
4630 // an ambiguity or a function that is deleted or inaccessible from the
4631 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004632 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4633 0);
4634 if (!CopyOper || CopyOper->isDeleted())
4635 return true;
4636 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004637 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004638 }
4639
4640 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4641 FE = RD->field_end();
4642 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004643 if (FI->isUnnamedBitfield())
4644 continue;
4645
Alexis Huntb2f27802011-05-14 05:23:24 +00004646 QualType FieldType = Context.getBaseElementType(FI->getType());
4647
4648 // -- a non-static data member of reference type
4649 if (FieldType->isReferenceType())
4650 return true;
4651
4652 // -- a non-static data member of const non-class type (or array thereof)
4653 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4654 return true;
4655
4656 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4657
4658 if (FieldRecord) {
4659 // This is an anonymous union
4660 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4661 // Anonymous unions inside unions do not variant members create
4662 if (!Union) {
4663 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4664 UE = FieldRecord->field_end();
4665 UI != UE; ++UI) {
4666 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4667 CXXRecordDecl *UnionFieldRecord =
4668 UnionFieldType->getAsCXXRecordDecl();
4669
4670 // -- a variant member with a non-trivial [copy] assignment operator
4671 // and X is a union-like class
4672 if (UnionFieldRecord &&
4673 !UnionFieldRecord->hasTrivialCopyAssignment())
4674 return true;
4675 }
4676 }
4677
4678 // Don't try to initalize an anonymous union
4679 continue;
4680 // -- a variant member with a non-trivial [copy] assignment operator
4681 // and X is a union-like class
4682 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4683 return true;
4684 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004685
Alexis Hunt491ec602011-06-21 23:42:56 +00004686 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4687 false, 0);
4688 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004689 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004690 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004691 return true;
4692 }
4693 }
4694
4695 return false;
4696}
4697
Sebastian Redl22653ba2011-08-30 19:58:05 +00004698bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4699 CXXRecordDecl *RD = MD->getParent();
4700 assert(!RD->isDependentType() && "do deletion after instantiation");
4701 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4702 return false;
4703
4704 SourceLocation Loc = MD->getLocation();
4705
4706 // Do access control from the constructor
4707 ContextRAII MethodContext(*this, MD);
4708
4709 bool Union = RD->isUnion();
4710
4711 // We do this because we should never actually use an anonymous
4712 // union's constructor.
4713 if (Union && RD->isAnonymousStructOrUnion())
4714 return false;
4715
4716 // C++0x [class.copy]/20
4717 // A defaulted [move] assignment operator for class X is defined as deleted
4718 // if X has:
4719
4720 // -- for the move constructor, [...] any direct or indirect virtual base
4721 // class.
4722 if (RD->getNumVBases() != 0)
4723 return true;
4724
4725 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4726 BE = RD->bases_end();
4727 BI != BE; ++BI) {
4728
4729 QualType BaseType = BI->getType();
4730 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4731 assert(BaseDecl && "base isn't a CXXRecordDecl");
4732
4733 // -- a [direct base class] B that cannot be [moved] because overload
4734 // resolution, as applied to B's [move] assignment operator, results in
4735 // an ambiguity or a function that is deleted or inaccessible from the
4736 // assignment operator
4737 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4738 if (!MoveOper || MoveOper->isDeleted())
4739 return true;
4740 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4741 return true;
4742
4743 // -- for the move assignment operator, a [direct base class] with a type
4744 // that does not have a move assignment operator and is not trivially
4745 // copyable.
4746 if (!MoveOper->isMoveAssignmentOperator() &&
4747 !BaseDecl->isTriviallyCopyable())
4748 return true;
4749 }
4750
4751 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4752 FE = RD->field_end();
4753 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004754 if (FI->isUnnamedBitfield())
4755 continue;
4756
Sebastian Redl22653ba2011-08-30 19:58:05 +00004757 QualType FieldType = Context.getBaseElementType(FI->getType());
4758
4759 // -- a non-static data member of reference type
4760 if (FieldType->isReferenceType())
4761 return true;
4762
4763 // -- a non-static data member of const non-class type (or array thereof)
4764 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4765 return true;
4766
4767 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4768
4769 if (FieldRecord) {
4770 // This is an anonymous union
4771 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4772 // Anonymous unions inside unions do not variant members create
4773 if (!Union) {
4774 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4775 UE = FieldRecord->field_end();
4776 UI != UE; ++UI) {
4777 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4778 CXXRecordDecl *UnionFieldRecord =
4779 UnionFieldType->getAsCXXRecordDecl();
4780
4781 // -- a variant member with a non-trivial [move] assignment operator
4782 // and X is a union-like class
4783 if (UnionFieldRecord &&
4784 !UnionFieldRecord->hasTrivialMoveAssignment())
4785 return true;
4786 }
4787 }
4788
4789 // Don't try to initalize an anonymous union
4790 continue;
4791 // -- a variant member with a non-trivial [move] assignment operator
4792 // and X is a union-like class
4793 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4794 return true;
4795 }
4796
4797 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4798 if (!MoveOper || MoveOper->isDeleted())
4799 return true;
4800 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4801 return true;
4802
4803 // -- for the move assignment operator, a [non-static data member] with a
4804 // type that does not have a move assignment operator and is not
4805 // trivially copyable.
4806 if (!MoveOper->isMoveAssignmentOperator() &&
4807 !FieldRecord->isTriviallyCopyable())
4808 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004809 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004810 }
4811
4812 return false;
4813}
4814
Alexis Huntf91729462011-05-12 22:46:25 +00004815bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4816 CXXRecordDecl *RD = DD->getParent();
4817 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004818 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004819 return false;
4820
Alexis Hunte77a28f2011-05-18 03:41:58 +00004821 SourceLocation Loc = DD->getLocation();
4822
Alexis Huntf91729462011-05-12 22:46:25 +00004823 // Do access control from the destructor
4824 ContextRAII CtorContext(*this, DD);
4825
4826 bool Union = RD->isUnion();
4827
Alexis Hunt913820d2011-05-13 06:10:58 +00004828 // We do this because we should never actually use an anonymous
4829 // union's destructor.
4830 if (Union && RD->isAnonymousStructOrUnion())
4831 return false;
4832
Alexis Huntf91729462011-05-12 22:46:25 +00004833 // C++0x [class.dtor]p5
4834 // A defaulted destructor for a class X is defined as deleted if:
4835 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4836 BE = RD->bases_end();
4837 BI != BE; ++BI) {
4838 // We'll handle this one later
4839 if (BI->isVirtual())
4840 continue;
4841
4842 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4843 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4844 assert(BaseDtor && "base has no destructor");
4845
4846 // -- any direct or virtual base class has a deleted destructor or
4847 // a destructor that is inaccessible from the defaulted destructor
4848 if (BaseDtor->isDeleted())
4849 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004850 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004851 AR_accessible)
4852 return true;
4853 }
4854
4855 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4856 BE = RD->vbases_end();
4857 BI != BE; ++BI) {
4858 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4859 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4860 assert(BaseDtor && "base has no destructor");
4861
4862 // -- any direct or virtual base class has a deleted destructor or
4863 // a destructor that is inaccessible from the defaulted destructor
4864 if (BaseDtor->isDeleted())
4865 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004866 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004867 AR_accessible)
4868 return true;
4869 }
4870
4871 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4872 FE = RD->field_end();
4873 FI != FE; ++FI) {
4874 QualType FieldType = Context.getBaseElementType(FI->getType());
4875 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4876 if (FieldRecord) {
4877 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4878 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4879 UE = FieldRecord->field_end();
4880 UI != UE; ++UI) {
4881 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4882 CXXRecordDecl *UnionFieldRecord =
4883 UnionFieldType->getAsCXXRecordDecl();
4884
4885 // -- X is a union-like class that has a variant member with a non-
4886 // trivial destructor.
4887 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4888 return true;
4889 }
4890 // Technically we are supposed to do this next check unconditionally.
4891 // But that makes absolutely no sense.
4892 } else {
4893 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4894
4895 // -- any of the non-static data members has class type M (or array
4896 // thereof) and M has a deleted destructor or a destructor that is
4897 // inaccessible from the defaulted destructor
4898 if (FieldDtor->isDeleted())
4899 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004900 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004901 AR_accessible)
4902 return true;
4903
4904 // -- X is a union-like class that has a variant member with a non-
4905 // trivial destructor.
4906 if (Union && !FieldDtor->isTrivial())
4907 return true;
4908 }
4909 }
4910 }
4911
4912 if (DD->isVirtual()) {
4913 FunctionDecl *OperatorDelete = 0;
4914 DeclarationName Name =
4915 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004916 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004917 false))
4918 return true;
4919 }
4920
4921
4922 return false;
4923}
4924
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004925/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004926namespace {
4927 struct FindHiddenVirtualMethodData {
4928 Sema *S;
4929 CXXMethodDecl *Method;
4930 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004931 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004932 };
4933}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004934
4935/// \brief Member lookup function that determines whether a given C++
4936/// method overloads virtual methods in a base class without overriding any,
4937/// to be used with CXXRecordDecl::lookupInBases().
4938static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4939 CXXBasePath &Path,
4940 void *UserData) {
4941 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4942
4943 FindHiddenVirtualMethodData &Data
4944 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4945
4946 DeclarationName Name = Data.Method->getDeclName();
4947 assert(Name.getNameKind() == DeclarationName::Identifier);
4948
4949 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004950 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004951 for (Path.Decls = BaseRecord->lookup(Name);
4952 Path.Decls.first != Path.Decls.second;
4953 ++Path.Decls.first) {
4954 NamedDecl *D = *Path.Decls.first;
4955 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004956 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004957 foundSameNameMethod = true;
4958 // Interested only in hidden virtual methods.
4959 if (!MD->isVirtual())
4960 continue;
4961 // If the method we are checking overrides a method from its base
4962 // don't warn about the other overloaded methods.
4963 if (!Data.S->IsOverload(Data.Method, MD, false))
4964 return true;
4965 // Collect the overload only if its hidden.
4966 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4967 overloadedMethods.push_back(MD);
4968 }
4969 }
4970
4971 if (foundSameNameMethod)
4972 Data.OverloadedMethods.append(overloadedMethods.begin(),
4973 overloadedMethods.end());
4974 return foundSameNameMethod;
4975}
4976
4977/// \brief See if a method overloads virtual methods in a base class without
4978/// overriding any.
4979void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4980 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00004981 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004982 return;
4983 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4984 return;
4985
4986 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4987 /*bool RecordPaths=*/false,
4988 /*bool DetectVirtual=*/false);
4989 FindHiddenVirtualMethodData Data;
4990 Data.Method = MD;
4991 Data.S = this;
4992
4993 // Keep the base methods that were overriden or introduced in the subclass
4994 // by 'using' in a set. A base method not in this set is hidden.
4995 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4996 res.first != res.second; ++res.first) {
4997 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4998 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4999 E = MD->end_overridden_methods();
5000 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005001 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005002 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5003 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005004 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005005 }
5006
5007 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5008 !Data.OverloadedMethods.empty()) {
5009 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5010 << MD << (Data.OverloadedMethods.size() > 1);
5011
5012 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5013 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5014 Diag(overloadedMD->getLocation(),
5015 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5016 }
5017 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005018}
5019
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005020void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005021 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005022 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005023 SourceLocation RBrac,
5024 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005025 if (!TagDecl)
5026 return;
Mike Stump11289f42009-09-09 15:08:12 +00005027
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005028 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005029
David Blaikie751c5582011-09-22 02:58:26 +00005030 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005031 // strict aliasing violation!
5032 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005033 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005034
Douglas Gregor0be31a22010-07-02 17:43:08 +00005035 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005036 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005037}
5038
Douglas Gregor05379422008-11-03 17:51:48 +00005039/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5040/// special functions, such as the default constructor, copy
5041/// constructor, or destructor, to the given C++ class (C++
5042/// [special]p1). This routine can only be executed just before the
5043/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005044void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005045 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005046 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005047
Douglas Gregor54be3392010-07-01 17:57:27 +00005048 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00005049 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005050
Richard Smith966c1fb2011-12-24 21:56:24 +00005051 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5052 ++ASTContext::NumImplicitMoveConstructors;
5053
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005054 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5055 ++ASTContext::NumImplicitCopyAssignmentOperators;
5056
5057 // If we have a dynamic class, then the copy assignment operator may be
5058 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5059 // it shows up in the right place in the vtable and that we diagnose
5060 // problems with the implicit exception specification.
5061 if (ClassDecl->isDynamicClass())
5062 DeclareImplicitCopyAssignment(ClassDecl);
5063 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005064
Richard Smith966c1fb2011-12-24 21:56:24 +00005065 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5066 ++ASTContext::NumImplicitMoveAssignmentOperators;
5067
5068 // Likewise for the move assignment operator.
5069 if (ClassDecl->isDynamicClass())
5070 DeclareImplicitMoveAssignment(ClassDecl);
5071 }
5072
Douglas Gregor7454c562010-07-02 20:37:36 +00005073 if (!ClassDecl->hasUserDeclaredDestructor()) {
5074 ++ASTContext::NumImplicitDestructors;
5075
5076 // If we have a dynamic class, then the destructor may be virtual, so we
5077 // have to declare the destructor immediately. This ensures that, e.g., it
5078 // shows up in the right place in the vtable and that we diagnose problems
5079 // with the implicit exception specification.
5080 if (ClassDecl->isDynamicClass())
5081 DeclareImplicitDestructor(ClassDecl);
5082 }
Douglas Gregor05379422008-11-03 17:51:48 +00005083}
5084
Francois Pichet1c229c02011-04-22 22:18:13 +00005085void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5086 if (!D)
5087 return;
5088
5089 int NumParamList = D->getNumTemplateParameterLists();
5090 for (int i = 0; i < NumParamList; i++) {
5091 TemplateParameterList* Params = D->getTemplateParameterList(i);
5092 for (TemplateParameterList::iterator Param = Params->begin(),
5093 ParamEnd = Params->end();
5094 Param != ParamEnd; ++Param) {
5095 NamedDecl *Named = cast<NamedDecl>(*Param);
5096 if (Named->getDeclName()) {
5097 S->AddDecl(Named);
5098 IdResolver.AddDecl(Named);
5099 }
5100 }
5101 }
5102}
5103
John McCall48871652010-08-21 09:40:31 +00005104void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005105 if (!D)
5106 return;
5107
5108 TemplateParameterList *Params = 0;
5109 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5110 Params = Template->getTemplateParameters();
5111 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5112 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5113 Params = PartialSpec->getTemplateParameters();
5114 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005115 return;
5116
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005117 for (TemplateParameterList::iterator Param = Params->begin(),
5118 ParamEnd = Params->end();
5119 Param != ParamEnd; ++Param) {
5120 NamedDecl *Named = cast<NamedDecl>(*Param);
5121 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005122 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005123 IdResolver.AddDecl(Named);
5124 }
5125 }
5126}
5127
John McCall48871652010-08-21 09:40:31 +00005128void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005129 if (!RecordD) return;
5130 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005131 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005132 PushDeclContext(S, Record);
5133}
5134
John McCall48871652010-08-21 09:40:31 +00005135void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005136 if (!RecordD) return;
5137 PopDeclContext();
5138}
5139
Douglas Gregor4d87df52008-12-16 21:30:33 +00005140/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5141/// parsing a top-level (non-nested) C++ class, and we are now
5142/// parsing those parts of the given Method declaration that could
5143/// not be parsed earlier (C++ [class.mem]p2), such as default
5144/// arguments. This action should enter the scope of the given
5145/// Method declaration as if we had just parsed the qualified method
5146/// name. However, it should not bring the parameters into scope;
5147/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005148void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005149}
5150
5151/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5152/// C++ method declaration. We're (re-)introducing the given
5153/// function parameter into scope for use in parsing later parts of
5154/// the method declaration. For example, we could see an
5155/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00005156void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005157 if (!ParamD)
5158 return;
Mike Stump11289f42009-09-09 15:08:12 +00005159
John McCall48871652010-08-21 09:40:31 +00005160 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00005161
5162 // If this parameter has an unparsed default argument, clear it out
5163 // to make way for the parsed default argument.
5164 if (Param->hasUnparsedDefaultArg())
5165 Param->setDefaultArg(0);
5166
John McCall48871652010-08-21 09:40:31 +00005167 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005168 if (Param->getDeclName())
5169 IdResolver.AddDecl(Param);
5170}
5171
5172/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5173/// processing the delayed method declaration for Method. The method
5174/// declaration is now considered finished. There may be a separate
5175/// ActOnStartOfFunctionDef action later (not necessarily
5176/// immediately!) for this method, if it was also defined inside the
5177/// class body.
John McCall48871652010-08-21 09:40:31 +00005178void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005179 if (!MethodD)
5180 return;
Mike Stump11289f42009-09-09 15:08:12 +00005181
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005182 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005183
John McCall48871652010-08-21 09:40:31 +00005184 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005185
5186 // Now that we have our default arguments, check the constructor
5187 // again. It could produce additional diagnostics or affect whether
5188 // the class has implicitly-declared destructors, among other
5189 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005190 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5191 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005192
5193 // Check the default arguments, which we may have added.
5194 if (!Method->isInvalidDecl())
5195 CheckCXXDefaultArguments(Method);
5196}
5197
Douglas Gregor831c93f2008-11-05 20:51:48 +00005198/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005199/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005200/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005201/// emit diagnostics and set the invalid bit to true. In any case, the type
5202/// will be updated to reflect a well-formed type for the constructor and
5203/// returned.
5204QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005205 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005206 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005207
5208 // C++ [class.ctor]p3:
5209 // A constructor shall not be virtual (10.3) or static (9.4). A
5210 // constructor can be invoked for a const, volatile or const
5211 // volatile object. A constructor shall not be declared const,
5212 // volatile, or const volatile (9.3.2).
5213 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005214 if (!D.isInvalidType())
5215 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5216 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5217 << SourceRange(D.getIdentifierLoc());
5218 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005219 }
John McCall8e7d6562010-08-26 03:08:43 +00005220 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005221 if (!D.isInvalidType())
5222 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5223 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5224 << SourceRange(D.getIdentifierLoc());
5225 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005226 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005227 }
Mike Stump11289f42009-09-09 15:08:12 +00005228
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005229 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005230 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005231 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005232 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5233 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005234 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005235 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5236 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005237 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005238 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5239 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005240 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005241 }
Mike Stump11289f42009-09-09 15:08:12 +00005242
Douglas Gregordb9d6642011-01-26 05:01:58 +00005243 // C++0x [class.ctor]p4:
5244 // A constructor shall not be declared with a ref-qualifier.
5245 if (FTI.hasRefQualifier()) {
5246 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5247 << FTI.RefQualifierIsLValueRef
5248 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5249 D.setInvalidType();
5250 }
5251
Douglas Gregor831c93f2008-11-05 20:51:48 +00005252 // Rebuild the function type "R" without any type qualifiers (in
5253 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005254 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005255 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005256 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5257 return R;
5258
5259 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5260 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005261 EPI.RefQualifier = RQ_None;
5262
Chris Lattner38378bf2009-04-25 08:28:21 +00005263 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005264 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005265}
5266
Douglas Gregor4d87df52008-12-16 21:30:33 +00005267/// CheckConstructor - Checks a fully-formed constructor for
5268/// well-formedness, issuing any diagnostics required. Returns true if
5269/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005270void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005271 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005272 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5273 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005274 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005275
5276 // C++ [class.copy]p3:
5277 // A declaration of a constructor for a class X is ill-formed if
5278 // its first parameter is of type (optionally cv-qualified) X and
5279 // either there are no other parameters or else all other
5280 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005281 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005282 ((Constructor->getNumParams() == 1) ||
5283 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005284 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5285 Constructor->getTemplateSpecializationKind()
5286 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005287 QualType ParamType = Constructor->getParamDecl(0)->getType();
5288 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5289 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005290 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005291 const char *ConstRef
5292 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5293 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005294 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005295 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005296
5297 // FIXME: Rather that making the constructor invalid, we should endeavor
5298 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005299 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005300 }
5301 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005302}
5303
John McCalldeb646e2010-08-04 01:04:25 +00005304/// CheckDestructor - Checks a fully-formed destructor definition for
5305/// well-formedness, issuing any diagnostics required. Returns true
5306/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005307bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005308 CXXRecordDecl *RD = Destructor->getParent();
5309
5310 if (Destructor->isVirtual()) {
5311 SourceLocation Loc;
5312
5313 if (!Destructor->isImplicit())
5314 Loc = Destructor->getLocation();
5315 else
5316 Loc = RD->getLocation();
5317
5318 // If we have a virtual destructor, look up the deallocation function
5319 FunctionDecl *OperatorDelete = 0;
5320 DeclarationName Name =
5321 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005322 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005323 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005324
Eli Friedmanfa0df832012-02-02 03:46:19 +00005325 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005326
5327 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005328 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005329
5330 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005331}
5332
Mike Stump11289f42009-09-09 15:08:12 +00005333static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005334FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5335 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5336 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005337 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005338}
5339
Douglas Gregor831c93f2008-11-05 20:51:48 +00005340/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5341/// the well-formednes of the destructor declarator @p D with type @p
5342/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005343/// emit diagnostics and set the declarator to invalid. Even if this happens,
5344/// will be updated to reflect a well-formed type for the destructor and
5345/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005346QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005347 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005348 // C++ [class.dtor]p1:
5349 // [...] A typedef-name that names a class is a class-name
5350 // (7.1.3); however, a typedef-name that names a class shall not
5351 // be used as the identifier in the declarator for a destructor
5352 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005353 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005354 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005355 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005356 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005357 else if (const TemplateSpecializationType *TST =
5358 DeclaratorType->getAs<TemplateSpecializationType>())
5359 if (TST->isTypeAlias())
5360 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5361 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005362
5363 // C++ [class.dtor]p2:
5364 // A destructor is used to destroy objects of its class type. A
5365 // destructor takes no parameters, and no return type can be
5366 // specified for it (not even void). The address of a destructor
5367 // shall not be taken. A destructor shall not be static. A
5368 // destructor can be invoked for a const, volatile or const
5369 // volatile object. A destructor shall not be declared const,
5370 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005371 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005372 if (!D.isInvalidType())
5373 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5374 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005375 << SourceRange(D.getIdentifierLoc())
5376 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5377
John McCall8e7d6562010-08-26 03:08:43 +00005378 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005379 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005380 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005381 // Destructors don't have return types, but the parser will
5382 // happily parse something like:
5383 //
5384 // class X {
5385 // float ~X();
5386 // };
5387 //
5388 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005389 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5390 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5391 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005392 }
Mike Stump11289f42009-09-09 15:08:12 +00005393
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005394 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005395 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005396 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005397 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5398 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005399 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005400 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5401 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005402 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005403 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5404 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005405 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005406 }
5407
Douglas Gregordb9d6642011-01-26 05:01:58 +00005408 // C++0x [class.dtor]p2:
5409 // A destructor shall not be declared with a ref-qualifier.
5410 if (FTI.hasRefQualifier()) {
5411 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5412 << FTI.RefQualifierIsLValueRef
5413 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5414 D.setInvalidType();
5415 }
5416
Douglas Gregor831c93f2008-11-05 20:51:48 +00005417 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005418 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005419 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5420
5421 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005422 FTI.freeArgs();
5423 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005424 }
5425
Mike Stump11289f42009-09-09 15:08:12 +00005426 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005427 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005428 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005429 D.setInvalidType();
5430 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005431
5432 // Rebuild the function type "R" without any type qualifiers or
5433 // parameters (in case any of the errors above fired) and with
5434 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005435 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005436 if (!D.isInvalidType())
5437 return R;
5438
Douglas Gregor95755162010-07-01 05:10:53 +00005439 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005440 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5441 EPI.Variadic = false;
5442 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005443 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005444 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005445}
5446
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005447/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5448/// well-formednes of the conversion function declarator @p D with
5449/// type @p R. If there are any errors in the declarator, this routine
5450/// will emit diagnostics and return true. Otherwise, it will return
5451/// false. Either way, the type @p R will be updated to reflect a
5452/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005453void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005454 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005455 // C++ [class.conv.fct]p1:
5456 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005457 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005458 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005459 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005460 if (!D.isInvalidType())
5461 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5462 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5463 << SourceRange(D.getIdentifierLoc());
5464 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005465 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005466 }
John McCall212fa2e2010-04-13 00:04:31 +00005467
5468 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5469
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005470 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005471 // Conversion functions don't have return types, but the parser will
5472 // happily parse something like:
5473 //
5474 // class X {
5475 // float operator bool();
5476 // };
5477 //
5478 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005479 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5480 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5481 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005482 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005483 }
5484
John McCall212fa2e2010-04-13 00:04:31 +00005485 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5486
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005487 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005488 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005489 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5490
5491 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005492 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005493 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005494 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005495 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005496 D.setInvalidType();
5497 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005498
John McCall212fa2e2010-04-13 00:04:31 +00005499 // Diagnose "&operator bool()" and other such nonsense. This
5500 // is actually a gcc extension which we don't support.
5501 if (Proto->getResultType() != ConvType) {
5502 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5503 << Proto->getResultType();
5504 D.setInvalidType();
5505 ConvType = Proto->getResultType();
5506 }
5507
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005508 // C++ [class.conv.fct]p4:
5509 // The conversion-type-id shall not represent a function type nor
5510 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005511 if (ConvType->isArrayType()) {
5512 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5513 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005514 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005515 } else if (ConvType->isFunctionType()) {
5516 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5517 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005518 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005519 }
5520
5521 // Rebuild the function type "R" without any parameters (in case any
5522 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005523 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005524 if (D.isInvalidType())
5525 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005526
Douglas Gregor5fb53972009-01-14 15:45:31 +00005527 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005528 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00005529 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith0bf8a4922011-10-18 20:49:44 +00005530 getLangOptions().CPlusPlus0x ?
5531 diag::warn_cxx98_compat_explicit_conversion_functions :
5532 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00005533 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005534}
5535
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005536/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5537/// the declaration of the given C++ conversion function. This routine
5538/// is responsible for recording the conversion function in the C++
5539/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005540Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005541 assert(Conversion && "Expected to receive a conversion function declaration");
5542
Douglas Gregor4287b372008-12-12 08:25:50 +00005543 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005544
5545 // Make sure we aren't redeclaring the conversion function.
5546 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005547
5548 // C++ [class.conv.fct]p1:
5549 // [...] A conversion function is never used to convert a
5550 // (possibly cv-qualified) object to the (possibly cv-qualified)
5551 // same object type (or a reference to it), to a (possibly
5552 // cv-qualified) base class of that type (or a reference to it),
5553 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005554 // FIXME: Suppress this warning if the conversion function ends up being a
5555 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005556 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005557 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005558 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005559 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005560 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5561 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005562 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005563 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005564 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5565 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005566 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005567 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005568 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005569 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005570 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005571 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005572 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005573 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005574 }
5575
Douglas Gregor457104e2010-09-29 04:25:11 +00005576 if (FunctionTemplateDecl *ConversionTemplate
5577 = Conversion->getDescribedFunctionTemplate())
5578 return ConversionTemplate;
5579
John McCall48871652010-08-21 09:40:31 +00005580 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005581}
5582
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005583//===----------------------------------------------------------------------===//
5584// Namespace Handling
5585//===----------------------------------------------------------------------===//
5586
John McCallb1be5232010-08-26 09:15:37 +00005587
5588
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005589/// ActOnStartNamespaceDef - This is called at the start of a namespace
5590/// definition.
John McCall48871652010-08-21 09:40:31 +00005591Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005592 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005593 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005594 SourceLocation IdentLoc,
5595 IdentifierInfo *II,
5596 SourceLocation LBrace,
5597 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005598 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5599 // For anonymous namespace, take the location of the left brace.
5600 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00005601 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00005602 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00005603 bool IsStd = false;
5604 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005605 Scope *DeclRegionScope = NamespcScope->getParent();
5606
Douglas Gregore57e7522012-01-07 09:11:48 +00005607 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005608 if (II) {
5609 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005610 // The identifier in an original-namespace-definition shall not
5611 // have been previously defined in the declarative region in
5612 // which the original-namespace-definition appears. The
5613 // identifier in an original-namespace-definition is the name of
5614 // the namespace. Subsequently in that declarative region, it is
5615 // treated as an original-namespace-name.
5616 //
5617 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005618 // look through using directives, just look for any ordinary names.
5619
5620 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00005621 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5622 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005623 NamedDecl *PrevDecl = 0;
5624 for (DeclContext::lookup_result R
Douglas Gregore57e7522012-01-07 09:11:48 +00005625 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005626 R.first != R.second; ++R.first) {
5627 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5628 PrevDecl = *R.first;
5629 break;
5630 }
5631 }
5632
Douglas Gregore57e7522012-01-07 09:11:48 +00005633 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5634
5635 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00005636 // This is an extended namespace definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005637 if (IsInline != PrevNS->isInline()) {
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005638 // inline-ness must match
Douglas Gregore57e7522012-01-07 09:11:48 +00005639 if (PrevNS->isInline()) {
Douglas Gregora9121972011-05-20 15:48:31 +00005640 // The user probably just forgot the 'inline', so suggest that it
5641 // be added back.
Douglas Gregore57e7522012-01-07 09:11:48 +00005642 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregora9121972011-05-20 15:48:31 +00005643 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5644 } else {
Douglas Gregore57e7522012-01-07 09:11:48 +00005645 Diag(Loc, diag::err_inline_namespace_mismatch)
5646 << IsInline;
Douglas Gregora9121972011-05-20 15:48:31 +00005647 }
Douglas Gregore57e7522012-01-07 09:11:48 +00005648 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5649
5650 IsInline = PrevNS->isInline();
5651 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005652 } else if (PrevDecl) {
5653 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005654 Diag(Loc, diag::err_redefinition_different_kind)
5655 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00005656 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005657 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00005658 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00005659 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005660 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005661 // This is the first "real" definition of the namespace "std", so update
5662 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005663 PrevNS = getStdNamespace();
5664 IsStd = true;
5665 AddToKnown = !IsInline;
5666 } else {
5667 // We've seen this namespace for the first time.
5668 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00005669 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005670 } else {
John McCall4fa53422009-10-01 00:25:31 +00005671 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00005672
5673 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00005674 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005675 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00005676 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005677 } else {
5678 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00005679 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005680 }
5681
Douglas Gregore57e7522012-01-07 09:11:48 +00005682 if (PrevNS && IsInline != PrevNS->isInline()) {
5683 // inline-ness must match
5684 Diag(Loc, diag::err_inline_namespace_mismatch)
5685 << IsInline;
5686 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005687
Douglas Gregore57e7522012-01-07 09:11:48 +00005688 // Recover by ignoring the new namespace's inline status.
5689 IsInline = PrevNS->isInline();
5690 }
5691 }
5692
5693 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5694 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005695 if (IsInvalid)
5696 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00005697
5698 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005699
Douglas Gregore57e7522012-01-07 09:11:48 +00005700 // FIXME: Should we be merging attributes?
5701 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005702 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00005703
5704 if (IsStd)
5705 StdNamespace = Namespc;
5706 if (AddToKnown)
5707 KnownNamespaces[Namespc] = false;
5708
5709 if (II) {
5710 PushOnScopeChains(Namespc, DeclRegionScope);
5711 } else {
5712 // Link the anonymous namespace into its parent.
5713 DeclContext *Parent = CurContext->getRedeclContext();
5714 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5715 TU->setAnonymousNamespace(Namespc);
5716 } else {
5717 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00005718 }
John McCall4fa53422009-10-01 00:25:31 +00005719
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005720 CurContext->addDecl(Namespc);
5721
John McCall4fa53422009-10-01 00:25:31 +00005722 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5723 // behaves as if it were replaced by
5724 // namespace unique { /* empty body */ }
5725 // using namespace unique;
5726 // namespace unique { namespace-body }
5727 // where all occurrences of 'unique' in a translation unit are
5728 // replaced by the same identifier and this identifier differs
5729 // from all other identifiers in the entire program.
5730
5731 // We just create the namespace with an empty name and then add an
5732 // implicit using declaration, just like the standard suggests.
5733 //
5734 // CodeGen enforces the "universally unique" aspect by giving all
5735 // declarations semantically contained within an anonymous
5736 // namespace internal linkage.
5737
Douglas Gregore57e7522012-01-07 09:11:48 +00005738 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00005739 UsingDirectiveDecl* UD
5740 = UsingDirectiveDecl::Create(Context, CurContext,
5741 /* 'using' */ LBrace,
5742 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005743 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005744 /* identifier */ SourceLocation(),
5745 Namespc,
5746 /* Ancestor */ CurContext);
5747 UD->setImplicit();
5748 CurContext->addDecl(UD);
5749 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005750 }
5751
5752 // Although we could have an invalid decl (i.e. the namespace name is a
5753 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005754 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5755 // for the namespace has the declarations that showed up in that particular
5756 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005757 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005758 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005759}
5760
Sebastian Redla6602e92009-11-23 15:34:23 +00005761/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5762/// is a namespace alias, returns the namespace it points to.
5763static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5764 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5765 return AD->getNamespace();
5766 return dyn_cast_or_null<NamespaceDecl>(D);
5767}
5768
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005769/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5770/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005771void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005772 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5773 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005774 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005775 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005776 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005777 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005778}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005779
John McCall28a0cf72010-08-25 07:42:41 +00005780CXXRecordDecl *Sema::getStdBadAlloc() const {
5781 return cast_or_null<CXXRecordDecl>(
5782 StdBadAlloc.get(Context.getExternalSource()));
5783}
5784
5785NamespaceDecl *Sema::getStdNamespace() const {
5786 return cast_or_null<NamespaceDecl>(
5787 StdNamespace.get(Context.getExternalSource()));
5788}
5789
Douglas Gregorcdf87022010-06-29 17:53:46 +00005790/// \brief Retrieve the special "std" namespace, which may require us to
5791/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005792NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005793 if (!StdNamespace) {
5794 // The "std" namespace has not yet been defined, so build one implicitly.
5795 StdNamespace = NamespaceDecl::Create(Context,
5796 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005797 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005798 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005799 &PP.getIdentifierTable().get("std"),
5800 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005801 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005802 }
5803
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005804 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005805}
5806
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005807bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5808 assert(getLangOptions().CPlusPlus &&
5809 "Looking for std::initializer_list outside of C++.");
5810
5811 // We're looking for implicit instantiations of
5812 // template <typename E> class std::initializer_list.
5813
5814 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5815 return false;
5816
Sebastian Redl43144e72012-01-17 22:49:58 +00005817 ClassTemplateDecl *Template = 0;
5818 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005819
Sebastian Redl43144e72012-01-17 22:49:58 +00005820 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005821
Sebastian Redl43144e72012-01-17 22:49:58 +00005822 ClassTemplateSpecializationDecl *Specialization =
5823 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5824 if (!Specialization)
5825 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005826
Sebastian Redl43144e72012-01-17 22:49:58 +00005827 if (Specialization->getSpecializationKind() != TSK_ImplicitInstantiation)
5828 return false;
5829
5830 Template = Specialization->getSpecializedTemplate();
5831 Arguments = Specialization->getTemplateArgs().data();
5832 } else if (const TemplateSpecializationType *TST =
5833 Ty->getAs<TemplateSpecializationType>()) {
5834 Template = dyn_cast_or_null<ClassTemplateDecl>(
5835 TST->getTemplateName().getAsTemplateDecl());
5836 Arguments = TST->getArgs();
5837 }
5838 if (!Template)
5839 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005840
5841 if (!StdInitializerList) {
5842 // Haven't recognized std::initializer_list yet, maybe this is it.
5843 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5844 if (TemplateClass->getIdentifier() !=
5845 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00005846 !getStdNamespace()->InEnclosingNamespaceSetOf(
5847 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005848 return false;
5849 // This is a template called std::initializer_list, but is it the right
5850 // template?
5851 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005852 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005853 return false;
5854 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5855 return false;
5856
5857 // It's the right template.
5858 StdInitializerList = Template;
5859 }
5860
5861 if (Template != StdInitializerList)
5862 return false;
5863
5864 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00005865 if (Element)
5866 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005867 return true;
5868}
5869
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005870static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5871 NamespaceDecl *Std = S.getStdNamespace();
5872 if (!Std) {
5873 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5874 return 0;
5875 }
5876
5877 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5878 Loc, Sema::LookupOrdinaryName);
5879 if (!S.LookupQualifiedName(Result, Std)) {
5880 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5881 return 0;
5882 }
5883 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5884 if (!Template) {
5885 Result.suppressDiagnostics();
5886 // We found something weird. Complain about the first thing we found.
5887 NamedDecl *Found = *Result.begin();
5888 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5889 return 0;
5890 }
5891
5892 // We found some template called std::initializer_list. Now verify that it's
5893 // correct.
5894 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005895 if (Params->getMinRequiredArguments() != 1 ||
5896 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005897 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5898 return 0;
5899 }
5900
5901 return Template;
5902}
5903
5904QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5905 if (!StdInitializerList) {
5906 StdInitializerList = LookupStdInitializerList(*this, Loc);
5907 if (!StdInitializerList)
5908 return QualType();
5909 }
5910
5911 TemplateArgumentListInfo Args(Loc, Loc);
5912 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5913 Context.getTrivialTypeSourceInfo(Element,
5914 Loc)));
5915 return Context.getCanonicalType(
5916 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5917}
5918
Sebastian Redlbe24ec22012-01-17 22:50:14 +00005919bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5920 // C++ [dcl.init.list]p2:
5921 // A constructor is an initializer-list constructor if its first parameter
5922 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5923 // std::initializer_list<E> for some type E, and either there are no other
5924 // parameters or else all other parameters have default arguments.
5925 if (Ctor->getNumParams() < 1 ||
5926 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5927 return false;
5928
5929 QualType ArgType = Ctor->getParamDecl(0)->getType();
5930 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5931 ArgType = RT->getPointeeType().getUnqualifiedType();
5932
5933 return isStdInitializerList(ArgType, 0);
5934}
5935
Douglas Gregora172e082011-03-26 22:25:30 +00005936/// \brief Determine whether a using statement is in a context where it will be
5937/// apply in all contexts.
5938static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5939 switch (CurContext->getDeclKind()) {
5940 case Decl::TranslationUnit:
5941 return true;
5942 case Decl::LinkageSpec:
5943 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5944 default:
5945 return false;
5946 }
5947}
5948
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005949namespace {
5950
5951// Callback to only accept typo corrections that are namespaces.
5952class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5953 public:
5954 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5955 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5956 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5957 }
5958 return false;
5959 }
5960};
5961
5962}
5963
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005964static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5965 CXXScopeSpec &SS,
5966 SourceLocation IdentLoc,
5967 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005968 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005969 R.clear();
5970 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005971 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00005972 Validator)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005973 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5974 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5975 if (DeclContext *DC = S.computeDeclContext(SS, false))
5976 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5977 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5978 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5979 else
5980 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5981 << Ident << CorrectedQuotedStr
5982 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005983
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005984 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5985 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005986
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005987 Ident = Corrected.getCorrectionAsIdentifierInfo();
5988 R.addDecl(Corrected.getCorrectionDecl());
5989 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005990 }
5991 return false;
5992}
5993
John McCall48871652010-08-21 09:40:31 +00005994Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005995 SourceLocation UsingLoc,
5996 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005997 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005998 SourceLocation IdentLoc,
5999 IdentifierInfo *NamespcName,
6000 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006001 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6002 assert(NamespcName && "Invalid NamespcName.");
6003 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006004
6005 // This can only happen along a recovery path.
6006 while (S->getFlags() & Scope::TemplateParamScope)
6007 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006008 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006009
Douglas Gregor889ceb72009-02-03 19:21:40 +00006010 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006011 NestedNameSpecifier *Qualifier = 0;
6012 if (SS.isSet())
6013 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6014
Douglas Gregor34074322009-01-14 22:20:51 +00006015 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006016 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6017 LookupParsedName(R, S, &SS);
6018 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006019 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006020
Douglas Gregorcdf87022010-06-29 17:53:46 +00006021 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006022 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006023 // Allow "using namespace std;" or "using namespace ::std;" even if
6024 // "std" hasn't been defined yet, for GCC compatibility.
6025 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6026 NamespcName->isStr("std")) {
6027 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006028 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006029 R.resolveKind();
6030 }
6031 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006032 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006033 }
6034
John McCall9f3059a2009-10-09 21:13:30 +00006035 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006036 NamedDecl *Named = R.getFoundDecl();
6037 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6038 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006039 // C++ [namespace.udir]p1:
6040 // A using-directive specifies that the names in the nominated
6041 // namespace can be used in the scope in which the
6042 // using-directive appears after the using-directive. During
6043 // unqualified name lookup (3.4.1), the names appear as if they
6044 // were declared in the nearest enclosing namespace which
6045 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006046 // namespace. [Note: in this context, "contains" means "contains
6047 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006048
6049 // Find enclosing context containing both using-directive and
6050 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006051 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006052 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6053 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6054 CommonAncestor = CommonAncestor->getParent();
6055
Sebastian Redla6602e92009-11-23 15:34:23 +00006056 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006057 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006058 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006059
Douglas Gregora172e082011-03-26 22:25:30 +00006060 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00006061 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006062 Diag(IdentLoc, diag::warn_using_directive_in_header);
6063 }
6064
Douglas Gregor889ceb72009-02-03 19:21:40 +00006065 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006066 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006067 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006068 }
6069
Douglas Gregor889ceb72009-02-03 19:21:40 +00006070 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00006071 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006072}
6073
6074void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6075 // If scope has associated entity, then using directive is at namespace
6076 // or translation unit scope. We add UsingDirectiveDecls, into
6077 // it's lookup structure.
6078 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006079 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006080 else
6081 // Otherwise it is block-sope. using-directives will affect lookup
6082 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00006083 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006084}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006085
Douglas Gregorfec52632009-06-20 00:51:54 +00006086
John McCall48871652010-08-21 09:40:31 +00006087Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006088 AccessSpecifier AS,
6089 bool HasUsingKeyword,
6090 SourceLocation UsingLoc,
6091 CXXScopeSpec &SS,
6092 UnqualifiedId &Name,
6093 AttributeList *AttrList,
6094 bool IsTypeName,
6095 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006096 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006097
Douglas Gregor220f4272009-11-04 16:30:06 +00006098 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006099 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006100 case UnqualifiedId::IK_Identifier:
6101 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006102 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006103 case UnqualifiedId::IK_ConversionFunctionId:
6104 break;
6105
6106 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00006107 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00006108 // C++0x inherited constructors.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006109 Diag(Name.getSourceRange().getBegin(),
6110 getLangOptions().CPlusPlus0x ?
6111 diag::warn_cxx98_compat_using_decl_constructor :
6112 diag::err_using_decl_constructor)
6113 << SS.getRange();
6114
John McCall3969e302009-12-08 07:46:18 +00006115 if (getLangOptions().CPlusPlus0x) break;
6116
John McCall48871652010-08-21 09:40:31 +00006117 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006118
6119 case UnqualifiedId::IK_DestructorName:
6120 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6121 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006122 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006123
6124 case UnqualifiedId::IK_TemplateId:
6125 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6126 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006127 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006128 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006129
6130 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6131 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006132 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00006133 return 0;
John McCall3969e302009-12-08 07:46:18 +00006134
John McCalla0097262009-12-11 02:10:03 +00006135 // Warn about using declarations.
6136 // TODO: store that the declaration was written without 'using' and
6137 // talk about access decls instead of using decls in the
6138 // diagnostics.
6139 if (!HasUsingKeyword) {
6140 UsingLoc = Name.getSourceRange().getBegin();
6141
6142 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00006143 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00006144 }
6145
Douglas Gregorc4356532010-12-16 00:46:58 +00006146 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6147 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6148 return 0;
6149
John McCall3f746822009-11-17 05:59:44 +00006150 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006151 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006152 /* IsInstantiation */ false,
6153 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00006154 if (UD)
6155 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00006156
John McCall48871652010-08-21 09:40:31 +00006157 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00006158}
6159
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006160/// \brief Determine whether a using declaration considers the given
6161/// declarations as "equivalent", e.g., if they are redeclarations of
6162/// the same entity or are both typedefs of the same type.
6163static bool
6164IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6165 bool &SuppressRedeclaration) {
6166 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6167 SuppressRedeclaration = false;
6168 return true;
6169 }
6170
Richard Smithdda56e42011-04-15 14:24:37 +00006171 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6172 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006173 SuppressRedeclaration = true;
6174 return Context.hasSameType(TD1->getUnderlyingType(),
6175 TD2->getUnderlyingType());
6176 }
6177
6178 return false;
6179}
6180
6181
John McCall84d87672009-12-10 09:41:52 +00006182/// Determines whether to create a using shadow decl for a particular
6183/// decl, given the set of decls existing prior to this using lookup.
6184bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6185 const LookupResult &Previous) {
6186 // Diagnose finding a decl which is not from a base class of the
6187 // current class. We do this now because there are cases where this
6188 // function will silently decide not to build a shadow decl, which
6189 // will pre-empt further diagnostics.
6190 //
6191 // We don't need to do this in C++0x because we do the check once on
6192 // the qualifier.
6193 //
6194 // FIXME: diagnose the following if we care enough:
6195 // struct A { int foo; };
6196 // struct B : A { using A::foo; };
6197 // template <class T> struct C : A {};
6198 // template <class T> struct D : C<T> { using B::foo; } // <---
6199 // This is invalid (during instantiation) in C++03 because B::foo
6200 // resolves to the using decl in B, which is not a base class of D<T>.
6201 // We can't diagnose it immediately because C<T> is an unknown
6202 // specialization. The UsingShadowDecl in D<T> then points directly
6203 // to A::foo, which will look well-formed when we instantiate.
6204 // The right solution is to not collapse the shadow-decl chain.
6205 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6206 DeclContext *OrigDC = Orig->getDeclContext();
6207
6208 // Handle enums and anonymous structs.
6209 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6210 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6211 while (OrigRec->isAnonymousStructOrUnion())
6212 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6213
6214 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6215 if (OrigDC == CurContext) {
6216 Diag(Using->getLocation(),
6217 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006218 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006219 Diag(Orig->getLocation(), diag::note_using_decl_target);
6220 return true;
6221 }
6222
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006223 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00006224 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006225 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00006226 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006227 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006228 Diag(Orig->getLocation(), diag::note_using_decl_target);
6229 return true;
6230 }
6231 }
6232
6233 if (Previous.empty()) return false;
6234
6235 NamedDecl *Target = Orig;
6236 if (isa<UsingShadowDecl>(Target))
6237 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6238
John McCalla17e83e2009-12-11 02:33:26 +00006239 // If the target happens to be one of the previous declarations, we
6240 // don't have a conflict.
6241 //
6242 // FIXME: but we might be increasing its access, in which case we
6243 // should redeclare it.
6244 NamedDecl *NonTag = 0, *Tag = 0;
6245 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6246 I != E; ++I) {
6247 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006248 bool Result;
6249 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6250 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00006251
6252 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6253 }
6254
John McCall84d87672009-12-10 09:41:52 +00006255 if (Target->isFunctionOrFunctionTemplate()) {
6256 FunctionDecl *FD;
6257 if (isa<FunctionTemplateDecl>(Target))
6258 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6259 else
6260 FD = cast<FunctionDecl>(Target);
6261
6262 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00006263 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00006264 case Ovl_Overload:
6265 return false;
6266
6267 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00006268 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006269 break;
6270
6271 // We found a decl with the exact signature.
6272 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006273 // If we're in a record, we want to hide the target, so we
6274 // return true (without a diagnostic) to tell the caller not to
6275 // build a shadow decl.
6276 if (CurContext->isRecord())
6277 return true;
6278
6279 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00006280 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006281 break;
6282 }
6283
6284 Diag(Target->getLocation(), diag::note_using_decl_target);
6285 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6286 return true;
6287 }
6288
6289 // Target is not a function.
6290
John McCall84d87672009-12-10 09:41:52 +00006291 if (isa<TagDecl>(Target)) {
6292 // No conflict between a tag and a non-tag.
6293 if (!Tag) return false;
6294
John McCalle29c5cd2009-12-10 19:51:03 +00006295 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006296 Diag(Target->getLocation(), diag::note_using_decl_target);
6297 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6298 return true;
6299 }
6300
6301 // No conflict between a tag and a non-tag.
6302 if (!NonTag) return false;
6303
John McCalle29c5cd2009-12-10 19:51:03 +00006304 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006305 Diag(Target->getLocation(), diag::note_using_decl_target);
6306 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6307 return true;
6308}
6309
John McCall3f746822009-11-17 05:59:44 +00006310/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00006311UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00006312 UsingDecl *UD,
6313 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00006314
6315 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00006316 NamedDecl *Target = Orig;
6317 if (isa<UsingShadowDecl>(Target)) {
6318 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6319 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006320 }
6321
6322 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006323 = UsingShadowDecl::Create(Context, CurContext,
6324 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006325 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006326
6327 Shadow->setAccess(UD->getAccess());
6328 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6329 Shadow->setInvalidDecl();
6330
John McCall3f746822009-11-17 05:59:44 +00006331 if (S)
John McCall3969e302009-12-08 07:46:18 +00006332 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006333 else
John McCall3969e302009-12-08 07:46:18 +00006334 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006335
John McCall3969e302009-12-08 07:46:18 +00006336
John McCall84d87672009-12-10 09:41:52 +00006337 return Shadow;
6338}
John McCall3969e302009-12-08 07:46:18 +00006339
John McCall84d87672009-12-10 09:41:52 +00006340/// Hides a using shadow declaration. This is required by the current
6341/// using-decl implementation when a resolvable using declaration in a
6342/// class is followed by a declaration which would hide or override
6343/// one or more of the using decl's targets; for example:
6344///
6345/// struct Base { void foo(int); };
6346/// struct Derived : Base {
6347/// using Base::foo;
6348/// void foo(int);
6349/// };
6350///
6351/// The governing language is C++03 [namespace.udecl]p12:
6352///
6353/// When a using-declaration brings names from a base class into a
6354/// derived class scope, member functions in the derived class
6355/// override and/or hide member functions with the same name and
6356/// parameter types in a base class (rather than conflicting).
6357///
6358/// There are two ways to implement this:
6359/// (1) optimistically create shadow decls when they're not hidden
6360/// by existing declarations, or
6361/// (2) don't create any shadow decls (or at least don't make them
6362/// visible) until we've fully parsed/instantiated the class.
6363/// The problem with (1) is that we might have to retroactively remove
6364/// a shadow decl, which requires several O(n) operations because the
6365/// decl structures are (very reasonably) not designed for removal.
6366/// (2) avoids this but is very fiddly and phase-dependent.
6367void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006368 if (Shadow->getDeclName().getNameKind() ==
6369 DeclarationName::CXXConversionFunctionName)
6370 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6371
John McCall84d87672009-12-10 09:41:52 +00006372 // Remove it from the DeclContext...
6373 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006374
John McCall84d87672009-12-10 09:41:52 +00006375 // ...and the scope, if applicable...
6376 if (S) {
John McCall48871652010-08-21 09:40:31 +00006377 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00006378 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006379 }
6380
John McCall84d87672009-12-10 09:41:52 +00006381 // ...and the using decl.
6382 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6383
6384 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00006385 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00006386}
6387
John McCalle61f2ba2009-11-18 02:36:19 +00006388/// Builds a using declaration.
6389///
6390/// \param IsInstantiation - Whether this call arises from an
6391/// instantiation of an unresolved using declaration. We treat
6392/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00006393NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6394 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006395 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006396 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00006397 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006398 bool IsInstantiation,
6399 bool IsTypeName,
6400 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00006401 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006402 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00006403 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00006404
Anders Carlssonf038fc22009-08-28 05:49:21 +00006405 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00006406
Anders Carlsson59140b32009-08-28 03:16:11 +00006407 if (SS.isEmpty()) {
6408 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00006409 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00006410 }
Mike Stump11289f42009-09-09 15:08:12 +00006411
John McCall84d87672009-12-10 09:41:52 +00006412 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006413 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00006414 ForRedeclaration);
6415 Previous.setHideTags(false);
6416 if (S) {
6417 LookupName(Previous, S);
6418
6419 // It is really dumb that we have to do this.
6420 LookupResult::Filter F = Previous.makeFilter();
6421 while (F.hasNext()) {
6422 NamedDecl *D = F.next();
6423 if (!isDeclInScope(D, CurContext, S))
6424 F.erase();
6425 }
6426 F.done();
6427 } else {
6428 assert(IsInstantiation && "no scope in non-instantiation");
6429 assert(CurContext->isRecord() && "scope not record in instantiation");
6430 LookupQualifiedName(Previous, CurContext);
6431 }
6432
John McCall84d87672009-12-10 09:41:52 +00006433 // Check for invalid redeclarations.
6434 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6435 return 0;
6436
6437 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00006438 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6439 return 0;
6440
John McCall84c16cf2009-11-12 03:15:40 +00006441 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006442 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006443 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00006444 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00006445 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00006446 // FIXME: not all declaration name kinds are legal here
6447 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6448 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006449 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006450 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00006451 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006452 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6453 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00006454 }
John McCallb96ec562009-12-04 22:46:56 +00006455 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006456 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6457 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00006458 }
John McCallb96ec562009-12-04 22:46:56 +00006459 D->setAccess(AS);
6460 CurContext->addDecl(D);
6461
6462 if (!LookupContext) return D;
6463 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00006464
John McCall0b66eb32010-05-01 00:40:08 +00006465 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00006466 UD->setInvalidDecl();
6467 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00006468 }
6469
Sebastian Redl08905022011-02-05 19:23:19 +00006470 // Constructor inheriting using decls get special treatment.
6471 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00006472 if (CheckInheritedConstructorUsingDecl(UD))
6473 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00006474 return UD;
6475 }
6476
6477 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00006478
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006479 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00006480
John McCall3969e302009-12-08 07:46:18 +00006481 // Unlike most lookups, we don't always want to hide tag
6482 // declarations: tag names are visible through the using declaration
6483 // even if hidden by ordinary names, *except* in a dependent context
6484 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00006485 if (!IsInstantiation)
6486 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00006487
John McCall27b18f82009-11-17 02:14:36 +00006488 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00006489
John McCall9f3059a2009-10-09 21:13:30 +00006490 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00006491 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006492 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006493 UD->setInvalidDecl();
6494 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006495 }
6496
John McCallb96ec562009-12-04 22:46:56 +00006497 if (R.isAmbiguous()) {
6498 UD->setInvalidDecl();
6499 return UD;
6500 }
Mike Stump11289f42009-09-09 15:08:12 +00006501
John McCalle61f2ba2009-11-18 02:36:19 +00006502 if (IsTypeName) {
6503 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00006504 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006505 Diag(IdentLoc, diag::err_using_typename_non_type);
6506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6507 Diag((*I)->getUnderlyingDecl()->getLocation(),
6508 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006509 UD->setInvalidDecl();
6510 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006511 }
6512 } else {
6513 // If we asked for a non-typename and we got a type, error out,
6514 // but only if this is an instantiation of an unresolved using
6515 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00006516 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006517 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6518 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006519 UD->setInvalidDecl();
6520 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006521 }
Anders Carlsson59140b32009-08-28 03:16:11 +00006522 }
6523
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006524 // C++0x N2914 [namespace.udecl]p6:
6525 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00006526 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006527 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6528 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006529 UD->setInvalidDecl();
6530 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006531 }
Mike Stump11289f42009-09-09 15:08:12 +00006532
John McCall84d87672009-12-10 09:41:52 +00006533 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6534 if (!CheckUsingShadowDecl(UD, *I, Previous))
6535 BuildUsingShadowDecl(S, UD, *I);
6536 }
John McCall3f746822009-11-17 05:59:44 +00006537
6538 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006539}
6540
Sebastian Redl08905022011-02-05 19:23:19 +00006541/// Additional checks for a using declaration referring to a constructor name.
6542bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6543 if (UD->isTypeName()) {
6544 // FIXME: Cannot specify typename when specifying constructor
6545 return true;
6546 }
6547
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006548 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006549 assert(SourceType &&
6550 "Using decl naming constructor doesn't have type in scope spec.");
6551 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6552
6553 // Check whether the named type is a direct base class.
6554 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6555 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6556 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6557 BaseIt != BaseE; ++BaseIt) {
6558 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6559 if (CanonicalSourceType == BaseType)
6560 break;
6561 }
6562
6563 if (BaseIt == BaseE) {
6564 // Did not find SourceType in the bases.
6565 Diag(UD->getUsingLocation(),
6566 diag::err_using_decl_constructor_not_in_direct_base)
6567 << UD->getNameInfo().getSourceRange()
6568 << QualType(SourceType, 0) << TargetClass;
6569 return true;
6570 }
6571
6572 BaseIt->setInheritConstructors();
6573
6574 return false;
6575}
6576
John McCall84d87672009-12-10 09:41:52 +00006577/// Checks that the given using declaration is not an invalid
6578/// redeclaration. Note that this is checking only for the using decl
6579/// itself, not for any ill-formedness among the UsingShadowDecls.
6580bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6581 bool isTypeName,
6582 const CXXScopeSpec &SS,
6583 SourceLocation NameLoc,
6584 const LookupResult &Prev) {
6585 // C++03 [namespace.udecl]p8:
6586 // C++0x [namespace.udecl]p10:
6587 // A using-declaration is a declaration and can therefore be used
6588 // repeatedly where (and only where) multiple declarations are
6589 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006590 //
John McCall032092f2010-11-29 18:01:58 +00006591 // That's in non-member contexts.
6592 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006593 return false;
6594
6595 NestedNameSpecifier *Qual
6596 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6597
6598 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6599 NamedDecl *D = *I;
6600
6601 bool DTypename;
6602 NestedNameSpecifier *DQual;
6603 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6604 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006605 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006606 } else if (UnresolvedUsingValueDecl *UD
6607 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6608 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006609 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006610 } else if (UnresolvedUsingTypenameDecl *UD
6611 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6612 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006613 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006614 } else continue;
6615
6616 // using decls differ if one says 'typename' and the other doesn't.
6617 // FIXME: non-dependent using decls?
6618 if (isTypeName != DTypename) continue;
6619
6620 // using decls differ if they name different scopes (but note that
6621 // template instantiation can cause this check to trigger when it
6622 // didn't before instantiation).
6623 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6624 Context.getCanonicalNestedNameSpecifier(DQual))
6625 continue;
6626
6627 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006628 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006629 return true;
6630 }
6631
6632 return false;
6633}
6634
John McCall3969e302009-12-08 07:46:18 +00006635
John McCallb96ec562009-12-04 22:46:56 +00006636/// Checks that the given nested-name qualifier used in a using decl
6637/// in the current context is appropriately related to the current
6638/// scope. If an error is found, diagnoses it and returns true.
6639bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6640 const CXXScopeSpec &SS,
6641 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006642 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006643
John McCall3969e302009-12-08 07:46:18 +00006644 if (!CurContext->isRecord()) {
6645 // C++03 [namespace.udecl]p3:
6646 // C++0x [namespace.udecl]p8:
6647 // A using-declaration for a class member shall be a member-declaration.
6648
6649 // If we weren't able to compute a valid scope, it must be a
6650 // dependent class scope.
6651 if (!NamedContext || NamedContext->isRecord()) {
6652 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6653 << SS.getRange();
6654 return true;
6655 }
6656
6657 // Otherwise, everything is known to be fine.
6658 return false;
6659 }
6660
6661 // The current scope is a record.
6662
6663 // If the named context is dependent, we can't decide much.
6664 if (!NamedContext) {
6665 // FIXME: in C++0x, we can diagnose if we can prove that the
6666 // nested-name-specifier does not refer to a base class, which is
6667 // still possible in some cases.
6668
6669 // Otherwise we have to conservatively report that things might be
6670 // okay.
6671 return false;
6672 }
6673
6674 if (!NamedContext->isRecord()) {
6675 // Ideally this would point at the last name in the specifier,
6676 // but we don't have that level of source info.
6677 Diag(SS.getRange().getBegin(),
6678 diag::err_using_decl_nested_name_specifier_is_not_class)
6679 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6680 return true;
6681 }
6682
Douglas Gregor7c842292010-12-21 07:41:49 +00006683 if (!NamedContext->isDependentContext() &&
6684 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6685 return true;
6686
John McCall3969e302009-12-08 07:46:18 +00006687 if (getLangOptions().CPlusPlus0x) {
6688 // C++0x [namespace.udecl]p3:
6689 // In a using-declaration used as a member-declaration, the
6690 // nested-name-specifier shall name a base class of the class
6691 // being defined.
6692
6693 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6694 cast<CXXRecordDecl>(NamedContext))) {
6695 if (CurContext == NamedContext) {
6696 Diag(NameLoc,
6697 diag::err_using_decl_nested_name_specifier_is_current_class)
6698 << SS.getRange();
6699 return true;
6700 }
6701
6702 Diag(SS.getRange().getBegin(),
6703 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6704 << (NestedNameSpecifier*) SS.getScopeRep()
6705 << cast<CXXRecordDecl>(CurContext)
6706 << SS.getRange();
6707 return true;
6708 }
6709
6710 return false;
6711 }
6712
6713 // C++03 [namespace.udecl]p4:
6714 // A using-declaration used as a member-declaration shall refer
6715 // to a member of a base class of the class being defined [etc.].
6716
6717 // Salient point: SS doesn't have to name a base class as long as
6718 // lookup only finds members from base classes. Therefore we can
6719 // diagnose here only if we can prove that that can't happen,
6720 // i.e. if the class hierarchies provably don't intersect.
6721
6722 // TODO: it would be nice if "definitely valid" results were cached
6723 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6724 // need to be repeated.
6725
6726 struct UserData {
6727 llvm::DenseSet<const CXXRecordDecl*> Bases;
6728
6729 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6730 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6731 Data->Bases.insert(Base);
6732 return true;
6733 }
6734
6735 bool hasDependentBases(const CXXRecordDecl *Class) {
6736 return !Class->forallBases(collect, this);
6737 }
6738
6739 /// Returns true if the base is dependent or is one of the
6740 /// accumulated base classes.
6741 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6742 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6743 return !Data->Bases.count(Base);
6744 }
6745
6746 bool mightShareBases(const CXXRecordDecl *Class) {
6747 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6748 }
6749 };
6750
6751 UserData Data;
6752
6753 // Returns false if we find a dependent base.
6754 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6755 return false;
6756
6757 // Returns false if the class has a dependent base or if it or one
6758 // of its bases is present in the base set of the current context.
6759 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6760 return false;
6761
6762 Diag(SS.getRange().getBegin(),
6763 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6764 << (NestedNameSpecifier*) SS.getScopeRep()
6765 << cast<CXXRecordDecl>(CurContext)
6766 << SS.getRange();
6767
6768 return true;
John McCallb96ec562009-12-04 22:46:56 +00006769}
6770
Richard Smithdda56e42011-04-15 14:24:37 +00006771Decl *Sema::ActOnAliasDeclaration(Scope *S,
6772 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006773 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006774 SourceLocation UsingLoc,
6775 UnqualifiedId &Name,
6776 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006777 // Skip up to the relevant declaration scope.
6778 while (S->getFlags() & Scope::TemplateParamScope)
6779 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006780 assert((S->getFlags() & Scope::DeclScope) &&
6781 "got alias-declaration outside of declaration scope");
6782
6783 if (Type.isInvalid())
6784 return 0;
6785
6786 bool Invalid = false;
6787 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6788 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006789 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006790
6791 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6792 return 0;
6793
6794 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006795 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006796 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006797 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6798 TInfo->getTypeLoc().getBeginLoc());
6799 }
Richard Smithdda56e42011-04-15 14:24:37 +00006800
6801 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6802 LookupName(Previous, S);
6803
6804 // Warn about shadowing the name of a template parameter.
6805 if (Previous.isSingleResult() &&
6806 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00006807 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00006808 Previous.clear();
6809 }
6810
6811 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6812 "name in alias declaration must be an identifier");
6813 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6814 Name.StartLocation,
6815 Name.Identifier, TInfo);
6816
6817 NewTD->setAccess(AS);
6818
6819 if (Invalid)
6820 NewTD->setInvalidDecl();
6821
Richard Smith3f1b5d02011-05-05 21:57:07 +00006822 CheckTypedefForVariablyModifiedType(S, NewTD);
6823 Invalid |= NewTD->isInvalidDecl();
6824
Richard Smithdda56e42011-04-15 14:24:37 +00006825 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006826
6827 NamedDecl *NewND;
6828 if (TemplateParamLists.size()) {
6829 TypeAliasTemplateDecl *OldDecl = 0;
6830 TemplateParameterList *OldTemplateParams = 0;
6831
6832 if (TemplateParamLists.size() != 1) {
6833 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6834 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6835 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6836 }
6837 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6838
6839 // Only consider previous declarations in the same scope.
6840 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6841 /*ExplicitInstantiationOrSpecialization*/false);
6842 if (!Previous.empty()) {
6843 Redeclaration = true;
6844
6845 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6846 if (!OldDecl && !Invalid) {
6847 Diag(UsingLoc, diag::err_redefinition_different_kind)
6848 << Name.Identifier;
6849
6850 NamedDecl *OldD = Previous.getRepresentativeDecl();
6851 if (OldD->getLocation().isValid())
6852 Diag(OldD->getLocation(), diag::note_previous_definition);
6853
6854 Invalid = true;
6855 }
6856
6857 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6858 if (TemplateParameterListsAreEqual(TemplateParams,
6859 OldDecl->getTemplateParameters(),
6860 /*Complain=*/true,
6861 TPL_TemplateMatch))
6862 OldTemplateParams = OldDecl->getTemplateParameters();
6863 else
6864 Invalid = true;
6865
6866 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6867 if (!Invalid &&
6868 !Context.hasSameType(OldTD->getUnderlyingType(),
6869 NewTD->getUnderlyingType())) {
6870 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6871 // but we can't reasonably accept it.
6872 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6873 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6874 if (OldTD->getLocation().isValid())
6875 Diag(OldTD->getLocation(), diag::note_previous_definition);
6876 Invalid = true;
6877 }
6878 }
6879 }
6880
6881 // Merge any previous default template arguments into our parameters,
6882 // and check the parameter list.
6883 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6884 TPC_TypeAliasTemplate))
6885 return 0;
6886
6887 TypeAliasTemplateDecl *NewDecl =
6888 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6889 Name.Identifier, TemplateParams,
6890 NewTD);
6891
6892 NewDecl->setAccess(AS);
6893
6894 if (Invalid)
6895 NewDecl->setInvalidDecl();
6896 else if (OldDecl)
6897 NewDecl->setPreviousDeclaration(OldDecl);
6898
6899 NewND = NewDecl;
6900 } else {
6901 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6902 NewND = NewTD;
6903 }
Richard Smithdda56e42011-04-15 14:24:37 +00006904
6905 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006906 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006907
Richard Smith3f1b5d02011-05-05 21:57:07 +00006908 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006909}
6910
John McCall48871652010-08-21 09:40:31 +00006911Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006912 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006913 SourceLocation AliasLoc,
6914 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006915 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006916 SourceLocation IdentLoc,
6917 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006918
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006919 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006920 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6921 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006922
Anders Carlssondca83c42009-03-28 06:23:46 +00006923 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006924 NamedDecl *PrevDecl
6925 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6926 ForRedeclaration);
6927 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6928 PrevDecl = 0;
6929
6930 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006931 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006932 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006933 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006934 // FIXME: At some point, we'll want to create the (redundant)
6935 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006936 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006937 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006938 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006939 }
Mike Stump11289f42009-09-09 15:08:12 +00006940
Anders Carlssondca83c42009-03-28 06:23:46 +00006941 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6942 diag::err_redefinition_different_kind;
6943 Diag(AliasLoc, DiagID) << Alias;
6944 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006945 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006946 }
6947
John McCall27b18f82009-11-17 02:14:36 +00006948 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006949 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006950
John McCall9f3059a2009-10-09 21:13:30 +00006951 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006952 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006953 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006954 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006955 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006956 }
Mike Stump11289f42009-09-09 15:08:12 +00006957
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006958 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006959 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006960 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006961 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006962
John McCalld8d0d432010-02-16 06:53:13 +00006963 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006964 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006965}
6966
Douglas Gregora57478e2010-05-01 15:04:51 +00006967namespace {
6968 /// \brief Scoped object used to handle the state changes required in Sema
6969 /// to implicitly define the body of a C++ member function;
6970 class ImplicitlyDefinedFunctionScope {
6971 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006972 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006973
6974 public:
6975 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006976 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006977 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006978 S.PushFunctionScope();
6979 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6980 }
6981
6982 ~ImplicitlyDefinedFunctionScope() {
6983 S.PopExpressionEvaluationContext();
Eli Friedman71c80552012-01-05 03:35:19 +00006984 S.PopFunctionScopeInfo();
Douglas Gregora57478e2010-05-01 15:04:51 +00006985 }
6986 };
6987}
6988
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006989Sema::ImplicitExceptionSpecification
6990Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006991 // C++ [except.spec]p14:
6992 // An implicitly declared special member function (Clause 12) shall have an
6993 // exception-specification. [...]
6994 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006995 if (ClassDecl->isInvalidDecl())
6996 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006997
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006998 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006999 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7000 BEnd = ClassDecl->bases_end();
7001 B != BEnd; ++B) {
7002 if (B->isVirtual()) // Handled below.
7003 continue;
7004
Douglas Gregor9672f922010-07-03 00:47:00 +00007005 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7006 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007007 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7008 // If this is a deleted function, add it anyway. This might be conformant
7009 // with the standard. This might not. I'm not sure. It might not matter.
7010 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007011 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007012 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007013 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007014
7015 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007016 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7017 BEnd = ClassDecl->vbases_end();
7018 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007019 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7020 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007021 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7022 // If this is a deleted function, add it anyway. This might be conformant
7023 // with the standard. This might not. I'm not sure. It might not matter.
7024 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007025 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007026 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007027 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007028
7029 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007030 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7031 FEnd = ClassDecl->field_end();
7032 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00007033 if (F->hasInClassInitializer()) {
7034 if (Expr *E = F->getInClassInitializer())
7035 ExceptSpec.CalledExpr(E);
7036 else if (!F->isInvalidDecl())
7037 ExceptSpec.SetDelayed();
7038 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00007039 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00007040 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7041 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7042 // If this is a deleted function, add it anyway. This might be conformant
7043 // with the standard. This might not. I'm not sure. It might not matter.
7044 // In particular, the problem is that this function never gets called. It
7045 // might just be ill-formed because this function attempts to refer to
7046 // a deleted function here.
7047 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007048 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007049 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007050 }
John McCalldb40c7f2010-12-14 08:05:40 +00007051
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007052 return ExceptSpec;
7053}
7054
7055CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7056 CXXRecordDecl *ClassDecl) {
7057 // C++ [class.ctor]p5:
7058 // A default constructor for a class X is a constructor of class X
7059 // that can be called without an argument. If there is no
7060 // user-declared constructor for class X, a default constructor is
7061 // implicitly declared. An implicitly-declared default constructor
7062 // is an inline public member of its class.
7063 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7064 "Should not build implicit default constructor!");
7065
7066 ImplicitExceptionSpecification Spec =
7067 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7068 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00007069
Douglas Gregor6d880b12010-07-01 22:31:05 +00007070 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007071 CanQualType ClassType
7072 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007073 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007074 DeclarationName Name
7075 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007076 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00007077 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7078 Context, ClassDecl, ClassLoc, NameInfo,
7079 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7080 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7081 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7082 getLangOptions().CPlusPlus0x);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007083 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00007084 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007085 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00007086 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00007087
7088 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00007089 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7090
Douglas Gregor0be31a22010-07-02 17:43:08 +00007091 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00007092 PushOnScopeChains(DefaultCon, S, false);
7093 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007094
Alexis Huntd6da8762011-10-10 06:18:57 +00007095 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007096 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00007097
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007098 return DefaultCon;
7099}
7100
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007101void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7102 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00007103 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007104 !Constructor->doesThisDeclarationHaveABody() &&
7105 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007106 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007107
Anders Carlsson423f5d82010-04-23 16:04:08 +00007108 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00007109 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00007110
Douglas Gregora57478e2010-05-01 15:04:51 +00007111 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007112 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00007113 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007114 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007115 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007116 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00007117 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00007118 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00007119 }
Douglas Gregor73193272010-09-20 16:48:21 +00007120
7121 SourceLocation Loc = Constructor->getLocation();
7122 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7123
7124 Constructor->setUsed();
7125 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007126
7127 if (ASTMutationListener *L = getASTMutationListener()) {
7128 L->CompletedImplicitDefinition(Constructor);
7129 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007130}
7131
Richard Smith938f40b2011-06-11 17:19:42 +00007132/// Get any existing defaulted default constructor for the given class. Do not
7133/// implicitly define one if it does not exist.
7134static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7135 CXXRecordDecl *D) {
7136 ASTContext &Context = Self.Context;
7137 QualType ClassType = Context.getTypeDeclType(D);
7138 DeclarationName ConstructorName
7139 = Context.DeclarationNames.getCXXConstructorName(
7140 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7141
7142 DeclContext::lookup_const_iterator Con, ConEnd;
7143 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7144 Con != ConEnd; ++Con) {
7145 // A function template cannot be defaulted.
7146 if (isa<FunctionTemplateDecl>(*Con))
7147 continue;
7148
7149 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7150 if (Constructor->isDefaultConstructor())
7151 return Constructor->isDefaulted() ? Constructor : 0;
7152 }
7153 return 0;
7154}
7155
7156void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7157 if (!D) return;
7158 AdjustDeclIfTemplate(D);
7159
7160 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7161 CXXConstructorDecl *CtorDecl
7162 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7163
7164 if (!CtorDecl) return;
7165
7166 // Compute the exception specification for the default constructor.
7167 const FunctionProtoType *CtorTy =
7168 CtorDecl->getType()->castAs<FunctionProtoType>();
7169 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7170 ImplicitExceptionSpecification Spec =
7171 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7172 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7173 assert(EPI.ExceptionSpecType != EST_Delayed);
7174
7175 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7176 }
7177
7178 // If the default constructor is explicitly defaulted, checking the exception
7179 // specification is deferred until now.
7180 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7181 !ClassDecl->isDependentType())
7182 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7183}
7184
Sebastian Redl08905022011-02-05 19:23:19 +00007185void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7186 // We start with an initial pass over the base classes to collect those that
7187 // inherit constructors from. If there are none, we can forgo all further
7188 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007189 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00007190 BasesVector BasesToInheritFrom;
7191 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7192 BaseE = ClassDecl->bases_end();
7193 BaseIt != BaseE; ++BaseIt) {
7194 if (BaseIt->getInheritConstructors()) {
7195 QualType Base = BaseIt->getType();
7196 if (Base->isDependentType()) {
7197 // If we inherit constructors from anything that is dependent, just
7198 // abort processing altogether. We'll get another chance for the
7199 // instantiations.
7200 return;
7201 }
7202 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7203 }
7204 }
7205 if (BasesToInheritFrom.empty())
7206 return;
7207
7208 // Now collect the constructors that we already have in the current class.
7209 // Those take precedence over inherited constructors.
7210 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7211 // unless there is a user-declared constructor with the same signature in
7212 // the class where the using-declaration appears.
7213 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7214 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7215 CtorE = ClassDecl->ctor_end();
7216 CtorIt != CtorE; ++CtorIt) {
7217 ExistingConstructors.insert(
7218 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7219 }
7220
7221 Scope *S = getScopeForContext(ClassDecl);
7222 DeclarationName CreatedCtorName =
7223 Context.DeclarationNames.getCXXConstructorName(
7224 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7225
7226 // Now comes the true work.
7227 // First, we keep a map from constructor types to the base that introduced
7228 // them. Needed for finding conflicting constructors. We also keep the
7229 // actually inserted declarations in there, for pretty diagnostics.
7230 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7231 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7232 ConstructorToSourceMap InheritedConstructors;
7233 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7234 BaseE = BasesToInheritFrom.end();
7235 BaseIt != BaseE; ++BaseIt) {
7236 const RecordType *Base = *BaseIt;
7237 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7238 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7239 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7240 CtorE = BaseDecl->ctor_end();
7241 CtorIt != CtorE; ++CtorIt) {
7242 // Find the using declaration for inheriting this base's constructors.
7243 DeclarationName Name =
7244 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7245 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7246 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7247 SourceLocation UsingLoc = UD ? UD->getLocation() :
7248 ClassDecl->getLocation();
7249
7250 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7251 // from the class X named in the using-declaration consists of actual
7252 // constructors and notional constructors that result from the
7253 // transformation of defaulted parameters as follows:
7254 // - all non-template default constructors of X, and
7255 // - for each non-template constructor of X that has at least one
7256 // parameter with a default argument, the set of constructors that
7257 // results from omitting any ellipsis parameter specification and
7258 // successively omitting parameters with a default argument from the
7259 // end of the parameter-type-list.
7260 CXXConstructorDecl *BaseCtor = *CtorIt;
7261 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7262 const FunctionProtoType *BaseCtorType =
7263 BaseCtor->getType()->getAs<FunctionProtoType>();
7264
7265 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7266 maxParams = BaseCtor->getNumParams();
7267 params <= maxParams; ++params) {
7268 // Skip default constructors. They're never inherited.
7269 if (params == 0)
7270 continue;
7271 // Skip copy and move constructors for the same reason.
7272 if (CanBeCopyOrMove && params == 1)
7273 continue;
7274
7275 // Build up a function type for this particular constructor.
7276 // FIXME: The working paper does not consider that the exception spec
7277 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00007278 // source. This code doesn't yet, either. When it does, this code will
7279 // need to be delayed until after exception specifications and in-class
7280 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00007281 const Type *NewCtorType;
7282 if (params == maxParams)
7283 NewCtorType = BaseCtorType;
7284 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007285 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00007286 for (unsigned i = 0; i < params; ++i) {
7287 Args.push_back(BaseCtorType->getArgType(i));
7288 }
7289 FunctionProtoType::ExtProtoInfo ExtInfo =
7290 BaseCtorType->getExtProtoInfo();
7291 ExtInfo.Variadic = false;
7292 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7293 Args.data(), params, ExtInfo)
7294 .getTypePtr();
7295 }
7296 const Type *CanonicalNewCtorType =
7297 Context.getCanonicalType(NewCtorType);
7298
7299 // Now that we have the type, first check if the class already has a
7300 // constructor with this signature.
7301 if (ExistingConstructors.count(CanonicalNewCtorType))
7302 continue;
7303
7304 // Then we check if we have already declared an inherited constructor
7305 // with this signature.
7306 std::pair<ConstructorToSourceMap::iterator, bool> result =
7307 InheritedConstructors.insert(std::make_pair(
7308 CanonicalNewCtorType,
7309 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7310 if (!result.second) {
7311 // Already in the map. If it came from a different class, that's an
7312 // error. Not if it's from the same.
7313 CanQualType PreviousBase = result.first->second.first;
7314 if (CanonicalBase != PreviousBase) {
7315 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7316 const CXXConstructorDecl *PrevBaseCtor =
7317 PrevCtor->getInheritedConstructor();
7318 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7319
7320 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7321 Diag(BaseCtor->getLocation(),
7322 diag::note_using_decl_constructor_conflict_current_ctor);
7323 Diag(PrevBaseCtor->getLocation(),
7324 diag::note_using_decl_constructor_conflict_previous_ctor);
7325 Diag(PrevCtor->getLocation(),
7326 diag::note_using_decl_constructor_conflict_previous_using);
7327 }
7328 continue;
7329 }
7330
7331 // OK, we're there, now add the constructor.
7332 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00007333 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00007334 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7335 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00007336 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7337 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007338 /*ImplicitlyDeclared=*/true,
7339 // FIXME: Due to a defect in the standard, we treat inherited
7340 // constructors as constexpr even if that makes them ill-formed.
7341 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00007342 NewCtor->setAccess(BaseCtor->getAccess());
7343
7344 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007345 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00007346 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007347 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7348 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00007349 /*IdentifierInfo=*/0,
7350 BaseCtorType->getArgType(i),
7351 /*TInfo=*/0, SC_None,
7352 SC_None, /*DefaultArg=*/0));
7353 }
David Blaikie9c70e042011-09-21 18:16:56 +00007354 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00007355 NewCtor->setInheritedConstructor(BaseCtor);
7356
7357 PushOnScopeChains(NewCtor, S, false);
7358 ClassDecl->addDecl(NewCtor);
7359 result.first->second.second = NewCtor;
7360 }
7361 }
7362 }
7363}
7364
Alexis Huntf91729462011-05-12 22:46:25 +00007365Sema::ImplicitExceptionSpecification
7366Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00007367 // C++ [except.spec]p14:
7368 // An implicitly declared special member function (Clause 12) shall have
7369 // an exception-specification.
7370 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007371 if (ClassDecl->isInvalidDecl())
7372 return ExceptSpec;
7373
Douglas Gregorf1203042010-07-01 19:09:28 +00007374 // Direct base-class destructors.
7375 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7376 BEnd = ClassDecl->bases_end();
7377 B != BEnd; ++B) {
7378 if (B->isVirtual()) // Handled below.
7379 continue;
7380
7381 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7382 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007383 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007384 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007385
Douglas Gregorf1203042010-07-01 19:09:28 +00007386 // Virtual base-class destructors.
7387 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7388 BEnd = ClassDecl->vbases_end();
7389 B != BEnd; ++B) {
7390 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7391 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007392 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007393 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007394
Douglas Gregorf1203042010-07-01 19:09:28 +00007395 // Field destructors.
7396 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7397 FEnd = ClassDecl->field_end();
7398 F != FEnd; ++F) {
7399 if (const RecordType *RecordTy
7400 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7401 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007402 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007403 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007404
Alexis Huntf91729462011-05-12 22:46:25 +00007405 return ExceptSpec;
7406}
7407
7408CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7409 // C++ [class.dtor]p2:
7410 // If a class has no user-declared destructor, a destructor is
7411 // declared implicitly. An implicitly-declared destructor is an
7412 // inline public member of its class.
7413
7414 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00007415 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00007416 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7417
Douglas Gregor7454c562010-07-02 20:37:36 +00007418 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00007419 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007420
Douglas Gregorf1203042010-07-01 19:09:28 +00007421 CanQualType ClassType
7422 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007423 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00007424 DeclarationName Name
7425 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007426 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00007427 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007428 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7429 /*isInline=*/true,
7430 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00007431 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00007432 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00007433 Destructor->setImplicit();
7434 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00007435
7436 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00007437 ++ASTContext::NumImplicitDestructorsDeclared;
7438
7439 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007440 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00007441 PushOnScopeChains(Destructor, S, false);
7442 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00007443
7444 // This could be uniqued if it ever proves significant.
7445 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00007446
7447 if (ShouldDeleteDestructor(Destructor))
7448 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00007449
7450 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00007451
Douglas Gregorf1203042010-07-01 19:09:28 +00007452 return Destructor;
7453}
7454
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007455void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00007456 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007457 assert((Destructor->isDefaulted() &&
7458 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007459 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00007460 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007461 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007462
Douglas Gregor54818f02010-05-12 16:39:35 +00007463 if (Destructor->isInvalidDecl())
7464 return;
7465
Douglas Gregora57478e2010-05-01 15:04:51 +00007466 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007467
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007468 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00007469 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7470 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00007471
Douglas Gregor54818f02010-05-12 16:39:35 +00007472 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007473 Diag(CurrentLocation, diag::note_member_synthesized_at)
7474 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7475
7476 Destructor->setInvalidDecl();
7477 return;
7478 }
7479
Douglas Gregor73193272010-09-20 16:48:21 +00007480 SourceLocation Loc = Destructor->getLocation();
7481 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00007482 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007483 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007484 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007485
7486 if (ASTMutationListener *L = getASTMutationListener()) {
7487 L->CompletedImplicitDefinition(Destructor);
7488 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007489}
7490
Sebastian Redl623ea822011-05-19 05:13:44 +00007491void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7492 CXXDestructorDecl *destructor) {
7493 // C++11 [class.dtor]p3:
7494 // A declaration of a destructor that does not have an exception-
7495 // specification is implicitly considered to have the same exception-
7496 // specification as an implicit declaration.
7497 const FunctionProtoType *dtorType = destructor->getType()->
7498 getAs<FunctionProtoType>();
7499 if (dtorType->hasExceptionSpec())
7500 return;
7501
7502 ImplicitExceptionSpecification exceptSpec =
7503 ComputeDefaultedDtorExceptionSpec(classDecl);
7504
Chandler Carruth9a797572011-09-20 04:55:26 +00007505 // Replace the destructor's type, building off the existing one. Fortunately,
7506 // the only thing of interest in the destructor type is its extended info.
7507 // The return and arguments are fixed.
7508 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00007509 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7510 epi.NumExceptions = exceptSpec.size();
7511 epi.Exceptions = exceptSpec.data();
7512 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7513
7514 destructor->setType(ty);
7515
7516 // FIXME: If the destructor has a body that could throw, and the newly created
7517 // spec doesn't allow exceptions, we should emit a warning, because this
7518 // change in behavior can break conforming C++03 programs at runtime.
7519 // However, we don't have a body yet, so it needs to be done somewhere else.
7520}
7521
Sebastian Redl22653ba2011-08-30 19:58:05 +00007522/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00007523/// \c To.
7524///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007525/// This routine is used to copy/move the members of a class with an
7526/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00007527/// copied are arrays, this routine builds for loops to copy them.
7528///
7529/// \param S The Sema object used for type-checking.
7530///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007531/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007532///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007533/// \param T The type of the expressions being copied/moved. Both expressions
7534/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007535///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007536/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007537///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007538/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007539///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007540/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007541/// Otherwise, it's a non-static member subobject.
7542///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007543/// \param Copying Whether we're copying or moving.
7544///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007545/// \param Depth Internal parameter recording the depth of the recursion.
7546///
7547/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007548static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007549BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007550 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007551 bool CopyingBaseSubobject, bool Copying,
7552 unsigned Depth = 0) {
7553 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007554 // Each subobject is assigned in the manner appropriate to its type:
7555 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007556 // - if the subobject is of class type, as if by a call to operator= with
7557 // the subobject as the object expression and the corresponding
7558 // subobject of x as a single function argument (as if by explicit
7559 // qualification; that is, ignoring any possible virtual overriding
7560 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007561 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7562 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7563
7564 // Look for operator=.
7565 DeclarationName Name
7566 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7567 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7568 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7569
Sebastian Redl22653ba2011-08-30 19:58:05 +00007570 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007571 LookupResult::Filter F = OpLookup.makeFilter();
7572 while (F.hasNext()) {
7573 NamedDecl *D = F.next();
7574 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007575 if (Copying ? Method->isCopyAssignmentOperator() :
7576 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007577 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007578
Douglas Gregorb139cd52010-05-01 20:49:11 +00007579 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007580 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007581 F.done();
7582
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007583 // Suppress the protected check (C++ [class.protected]) for each of the
7584 // assignment operators we found. This strange dance is required when
7585 // we're assigning via a base classes's copy-assignment operator. To
7586 // ensure that we're getting the right base class subobject (without
7587 // ambiguities), we need to cast "this" to that subobject type; to
7588 // ensure that we don't go through the virtual call mechanism, we need
7589 // to qualify the operator= name with the base class (see below). However,
7590 // this means that if the base class has a protected copy assignment
7591 // operator, the protected member access check will fail. So, we
7592 // rewrite "protected" access to "public" access in this case, since we
7593 // know by construction that we're calling from a derived class.
7594 if (CopyingBaseSubobject) {
7595 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7596 L != LEnd; ++L) {
7597 if (L.getAccess() == AS_protected)
7598 L.setAccess(AS_public);
7599 }
7600 }
7601
Douglas Gregorb139cd52010-05-01 20:49:11 +00007602 // Create the nested-name-specifier that will be used to qualify the
7603 // reference to operator=; this is required to suppress the virtual
7604 // call mechanism.
7605 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00007606 SS.MakeTrivial(S.Context,
7607 NestedNameSpecifier::Create(S.Context, 0, false,
7608 T.getTypePtr()),
7609 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007610
7611 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007612 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007613 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00007614 /*TemplateKWLoc=*/SourceLocation(),
7615 /*FirstQualifierInScope=*/0,
7616 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007617 /*TemplateArgs=*/0,
7618 /*SuppressQualifierCheck=*/true);
7619 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007620 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007621
7622 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007623
John McCalldadc5752010-08-24 06:29:42 +00007624 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007625 OpEqualRef.takeAs<Expr>(),
7626 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007627 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007628 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007629
7630 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007631 }
John McCallab8c2732010-03-16 06:11:48 +00007632
Douglas Gregorb139cd52010-05-01 20:49:11 +00007633 // - if the subobject is of scalar type, the built-in assignment
7634 // operator is used.
7635 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7636 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007637 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007638 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007639 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007640
7641 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007642 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007643
7644 // - if the subobject is an array, each element is assigned, in the
7645 // manner appropriate to the element type;
7646
7647 // Construct a loop over the array bounds, e.g.,
7648 //
7649 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7650 //
7651 // that will copy each of the array elements.
7652 QualType SizeType = S.Context.getSizeType();
7653
7654 // Create the iteration variable.
7655 IdentifierInfo *IterationVarName = 0;
7656 {
7657 llvm::SmallString<8> Str;
7658 llvm::raw_svector_ostream OS(Str);
7659 OS << "__i" << Depth;
7660 IterationVarName = &S.Context.Idents.get(OS.str());
7661 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007662 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007663 IterationVarName, SizeType,
7664 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007665 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007666
7667 // Initialize the iteration variable to zero.
7668 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007669 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007670
7671 // Create a reference to the iteration variable; we'll use this several
7672 // times throughout.
7673 Expr *IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00007674 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007675 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00007676 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7677 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7678
Douglas Gregorb139cd52010-05-01 20:49:11 +00007679 // Create the DeclStmt that holds the iteration variable.
7680 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7681
7682 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007683 llvm::APInt Upper
7684 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007685 Expr *Comparison
Eli Friedman844f9452012-01-23 02:35:22 +00007686 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCall7decc9e2010-11-18 06:31:45 +00007687 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7688 BO_NE, S.Context.BoolTy,
7689 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007690
7691 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007692 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007693 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7694 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007695
7696 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007697 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007698 IterationVarRefRVal,
7699 Loc));
John McCallb268a282010-08-23 23:25:46 +00007700 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007701 IterationVarRefRVal,
7702 Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007703 if (!Copying) // Cast to rvalue
7704 From = CastForMoving(S, From);
7705
7706 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007707 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7708 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007709 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007710 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007711 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007712
7713 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007714 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007715 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007716 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007717 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007718}
7719
Alexis Hunt119f3652011-05-14 05:23:20 +00007720std::pair<Sema::ImplicitExceptionSpecification, bool>
7721Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7722 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007723 if (ClassDecl->isInvalidDecl())
7724 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7725
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007726 // C++ [class.copy]p10:
7727 // If the class definition does not explicitly declare a copy
7728 // assignment operator, one is declared implicitly.
7729 // The implicitly-defined copy assignment operator for a class X
7730 // will have the form
7731 //
7732 // X& X::operator=(const X&)
7733 //
7734 // if
7735 bool HasConstCopyAssignment = true;
7736
7737 // -- each direct base class B of X has a copy assignment operator
7738 // whose parameter is of type const B&, const volatile B& or B,
7739 // and
7740 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7741 BaseEnd = ClassDecl->bases_end();
7742 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007743 // We'll handle this below
7744 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7745 continue;
7746
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007747 assert(!Base->getType()->isDependentType() &&
7748 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007749 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7750 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7751 &HasConstCopyAssignment);
7752 }
7753
Richard Smith0bf8a4922011-10-18 20:49:44 +00007754 // In C++11, the above citation has "or virtual" added
Alexis Hunt491ec602011-06-21 23:42:56 +00007755 if (LangOpts.CPlusPlus0x) {
7756 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7757 BaseEnd = ClassDecl->vbases_end();
7758 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7759 assert(!Base->getType()->isDependentType() &&
7760 "Cannot generate implicit members for class with dependent bases.");
7761 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7762 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7763 &HasConstCopyAssignment);
7764 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007765 }
7766
7767 // -- for all the nonstatic data members of X that are of a class
7768 // type M (or array thereof), each such class type has a copy
7769 // assignment operator whose parameter is of type const M&,
7770 // const volatile M& or M.
7771 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7772 FieldEnd = ClassDecl->field_end();
7773 HasConstCopyAssignment && Field != FieldEnd;
7774 ++Field) {
7775 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007776 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7777 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7778 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007779 }
7780 }
7781
7782 // Otherwise, the implicitly declared copy assignment operator will
7783 // have the form
7784 //
7785 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007786
Douglas Gregor68e11362010-07-01 17:48:08 +00007787 // C++ [except.spec]p14:
7788 // An implicitly declared special member function (Clause 12) shall have an
7789 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007790
7791 // It is unspecified whether or not an implicit copy assignment operator
7792 // attempts to deduplicate calls to assignment operators of virtual bases are
7793 // made. As such, this exception specification is effectively unspecified.
7794 // Based on a similar decision made for constness in C++0x, we're erring on
7795 // the side of assuming such calls to be made regardless of whether they
7796 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007797 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007798 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007799 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7800 BaseEnd = ClassDecl->bases_end();
7801 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007802 if (Base->isVirtual())
7803 continue;
7804
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007805 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007806 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007807 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7808 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007809 ExceptSpec.CalledDecl(CopyAssign);
7810 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007811
7812 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7813 BaseEnd = ClassDecl->vbases_end();
7814 Base != BaseEnd; ++Base) {
7815 CXXRecordDecl *BaseClassDecl
7816 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7817 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7818 ArgQuals, false, 0))
7819 ExceptSpec.CalledDecl(CopyAssign);
7820 }
7821
Douglas Gregor68e11362010-07-01 17:48:08 +00007822 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7823 FieldEnd = ClassDecl->field_end();
7824 Field != FieldEnd;
7825 ++Field) {
7826 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007827 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7828 if (CXXMethodDecl *CopyAssign =
7829 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7830 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007831 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007832 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007833
Alexis Hunt119f3652011-05-14 05:23:20 +00007834 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7835}
7836
7837CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7838 // Note: The following rules are largely analoguous to the copy
7839 // constructor rules. Note that virtual bases are not taken into account
7840 // for determining the argument type of the operator. Note also that
7841 // operators taking an object instead of a reference are allowed.
7842
7843 ImplicitExceptionSpecification Spec(Context);
7844 bool Const;
7845 llvm::tie(Spec, Const) =
7846 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7847
7848 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7849 QualType RetType = Context.getLValueReferenceType(ArgType);
7850 if (Const)
7851 ArgType = ArgType.withConst();
7852 ArgType = Context.getLValueReferenceType(ArgType);
7853
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007854 // An implicitly-declared copy assignment operator is an inline public
7855 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007856 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007857 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007858 SourceLocation ClassLoc = ClassDecl->getLocation();
7859 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007860 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007861 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007862 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007863 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007864 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007865 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007866 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007867 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007868 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007869 CopyAssignment->setImplicit();
7870 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007871
7872 // Add the parameter to the operator.
7873 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007874 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007875 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007876 SC_None,
7877 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007878 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007879
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007880 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007881 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007882
Douglas Gregor0be31a22010-07-02 17:43:08 +00007883 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007884 PushOnScopeChains(CopyAssignment, S, false);
7885 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007886
Nico Weber94e746d2012-01-23 03:19:29 +00007887 // C++0x [class.copy]p19:
7888 // .... If the class definition does not explicitly declare a copy
7889 // assignment operator, there is no user-declared move constructor, and
7890 // there is no user-declared move assignment operator, a copy assignment
7891 // operator is implicitly declared as defaulted.
7892 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber323076f2012-01-23 04:01:33 +00007893 !getLangOptions().MicrosoftMode) ||
7894 ClassDecl->hasUserDeclaredMoveAssignment() ||
Alexis Huntd74c85f2011-06-22 01:05:13 +00007895 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007896 CopyAssignment->setDeletedAsWritten();
7897
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007898 AddOverriddenMethods(ClassDecl, CopyAssignment);
7899 return CopyAssignment;
7900}
7901
Douglas Gregorb139cd52010-05-01 20:49:11 +00007902void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7903 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007904 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007905 CopyAssignOperator->isOverloadedOperator() &&
7906 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007907 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007908 "DefineImplicitCopyAssignment called for wrong function");
7909
7910 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7911
7912 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7913 CopyAssignOperator->setInvalidDecl();
7914 return;
7915 }
7916
7917 CopyAssignOperator->setUsed();
7918
7919 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007920 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007921
7922 // C++0x [class.copy]p30:
7923 // The implicitly-defined or explicitly-defaulted copy assignment operator
7924 // for a non-union class X performs memberwise copy assignment of its
7925 // subobjects. The direct base classes of X are assigned first, in the
7926 // order of their declaration in the base-specifier-list, and then the
7927 // immediate non-static data members of X are assigned, in the order in
7928 // which they were declared in the class definition.
7929
7930 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007931 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007932
7933 // The parameter for the "other" object, which we are copying from.
7934 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7935 Qualifiers OtherQuals = Other->getType().getQualifiers();
7936 QualType OtherRefType = Other->getType();
7937 if (const LValueReferenceType *OtherRef
7938 = OtherRefType->getAs<LValueReferenceType>()) {
7939 OtherRefType = OtherRef->getPointeeType();
7940 OtherQuals = OtherRefType.getQualifiers();
7941 }
7942
7943 // Our location for everything implicitly-generated.
7944 SourceLocation Loc = CopyAssignOperator->getLocation();
7945
7946 // Construct a reference to the "other" object. We'll be using this
7947 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007948 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007949 assert(OtherRef && "Reference to parameter cannot fail!");
7950
7951 // Construct the "this" pointer. We'll be using this throughout the generated
7952 // ASTs.
7953 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7954 assert(This && "Reference to this cannot fail!");
7955
7956 // Assign base classes.
7957 bool Invalid = false;
7958 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7959 E = ClassDecl->bases_end(); Base != E; ++Base) {
7960 // Form the assignment:
7961 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7962 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007963 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007964 Invalid = true;
7965 continue;
7966 }
7967
John McCallcf142162010-08-07 06:22:56 +00007968 CXXCastPath BasePath;
7969 BasePath.push_back(Base);
7970
Douglas Gregorb139cd52010-05-01 20:49:11 +00007971 // Construct the "from" expression, which is an implicit cast to the
7972 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007973 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007974 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7975 CK_UncheckedDerivedToBase,
7976 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007977
7978 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007979 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007980
7981 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007982 To = ImpCastExprToType(To.take(),
7983 Context.getCVRQualifiedType(BaseType,
7984 CopyAssignOperator->getTypeQualifiers()),
7985 CK_UncheckedDerivedToBase,
7986 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007987
7988 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007989 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007990 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007991 /*CopyingBaseSubobject=*/true,
7992 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007993 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007994 Diag(CurrentLocation, diag::note_member_synthesized_at)
7995 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7996 CopyAssignOperator->setInvalidDecl();
7997 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007998 }
7999
8000 // Success! Record the copy.
8001 Statements.push_back(Copy.takeAs<Expr>());
8002 }
8003
8004 // \brief Reference to the __builtin_memcpy function.
8005 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008006 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008007 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008008
8009 // Assign non-static members.
8010 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8011 FieldEnd = ClassDecl->field_end();
8012 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008013 if (Field->isUnnamedBitfield())
8014 continue;
8015
Douglas Gregorb139cd52010-05-01 20:49:11 +00008016 // Check for members of reference type; we can't copy those.
8017 if (Field->getType()->isReferenceType()) {
8018 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8019 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8020 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008021 Diag(CurrentLocation, diag::note_member_synthesized_at)
8022 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008023 Invalid = true;
8024 continue;
8025 }
8026
8027 // Check for members of const-qualified, non-class type.
8028 QualType BaseType = Context.getBaseElementType(Field->getType());
8029 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8030 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8031 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8032 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008033 Diag(CurrentLocation, diag::note_member_synthesized_at)
8034 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008035 Invalid = true;
8036 continue;
8037 }
John McCall1b1a1db2011-06-17 00:18:42 +00008038
8039 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008040 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8041 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008042
8043 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008044 if (FieldType->isIncompleteArrayType()) {
8045 assert(ClassDecl->hasFlexibleArrayMember() &&
8046 "Incomplete array type is not valid");
8047 continue;
8048 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008049
8050 // Build references to the field in the object we're copying from and to.
8051 CXXScopeSpec SS; // Intentionally empty
8052 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8053 LookupMemberName);
8054 MemberLookup.addDecl(*Field);
8055 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00008056 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00008057 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008058 SS, SourceLocation(), 0,
8059 MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00008060 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00008061 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008062 SS, SourceLocation(), 0,
8063 MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008064 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8065 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8066
8067 // If the field should be copied with __builtin_memcpy rather than via
8068 // explicit assignments, do so. This optimization only applies for arrays
8069 // of scalars and arrays of class type with trivial copy-assignment
8070 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00008071 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00008072 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008073 // Compute the size of the memory buffer to be copied.
8074 QualType SizeType = Context.getSizeType();
8075 llvm::APInt Size(Context.getTypeSize(SizeType),
8076 Context.getTypeSizeInChars(BaseType).getQuantity());
8077 for (const ConstantArrayType *Array
8078 = Context.getAsConstantArrayType(FieldType);
8079 Array;
8080 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00008081 llvm::APInt ArraySize
8082 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008083 Size *= ArraySize;
8084 }
8085
8086 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00008087 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8088 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008089
8090 bool NeedsCollectableMemCpy =
8091 (BaseType->isRecordType() &&
8092 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8093
8094 if (NeedsCollectableMemCpy) {
8095 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008096 // Create a reference to the __builtin_objc_memmove_collectable function.
8097 LookupResult R(*this,
8098 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008099 Loc, LookupOrdinaryName);
8100 LookupName(R, TUScope, true);
8101
8102 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8103 if (!CollectableMemCpy) {
8104 // Something went horribly wrong earlier, and we will have
8105 // complained about it.
8106 Invalid = true;
8107 continue;
8108 }
8109
8110 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8111 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008112 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008113 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8114 }
8115 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008116 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008117 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008118 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8119 LookupOrdinaryName);
8120 LookupName(R, TUScope, true);
8121
8122 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8123 if (!BuiltinMemCpy) {
8124 // Something went horribly wrong earlier, and we will have complained
8125 // about it.
8126 Invalid = true;
8127 continue;
8128 }
8129
8130 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8131 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008132 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008133 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8134 }
8135
John McCall37ad5512010-08-23 06:44:23 +00008136 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008137 CallArgs.push_back(To.takeAs<Expr>());
8138 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008139 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00008140 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008141 if (NeedsCollectableMemCpy)
8142 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008143 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008144 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008145 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008146 else
8147 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008148 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008149 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008150 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008151
Douglas Gregorb139cd52010-05-01 20:49:11 +00008152 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8153 Statements.push_back(Call.takeAs<Expr>());
8154 continue;
8155 }
8156
8157 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00008158 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008159 To.get(), From.get(),
8160 /*CopyingBaseSubobject=*/false,
8161 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008162 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008163 Diag(CurrentLocation, diag::note_member_synthesized_at)
8164 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8165 CopyAssignOperator->setInvalidDecl();
8166 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008167 }
8168
8169 // Success! Record the copy.
8170 Statements.push_back(Copy.takeAs<Stmt>());
8171 }
8172
8173 if (!Invalid) {
8174 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00008175 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008176
John McCalldadc5752010-08-24 06:29:42 +00008177 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008178 if (Return.isInvalid())
8179 Invalid = true;
8180 else {
8181 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00008182
8183 if (Trap.hasErrorOccurred()) {
8184 Diag(CurrentLocation, diag::note_member_synthesized_at)
8185 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8186 Invalid = true;
8187 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008188 }
8189 }
8190
8191 if (Invalid) {
8192 CopyAssignOperator->setInvalidDecl();
8193 return;
8194 }
8195
John McCalldadc5752010-08-24 06:29:42 +00008196 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00008197 /*isStmtExpr=*/false);
8198 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8199 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00008200
8201 if (ASTMutationListener *L = getASTMutationListener()) {
8202 L->CompletedImplicitDefinition(CopyAssignOperator);
8203 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008204}
8205
Sebastian Redl22653ba2011-08-30 19:58:05 +00008206Sema::ImplicitExceptionSpecification
8207Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8208 ImplicitExceptionSpecification ExceptSpec(Context);
8209
8210 if (ClassDecl->isInvalidDecl())
8211 return ExceptSpec;
8212
8213 // C++0x [except.spec]p14:
8214 // An implicitly declared special member function (Clause 12) shall have an
8215 // exception-specification. [...]
8216
8217 // It is unspecified whether or not an implicit move assignment operator
8218 // attempts to deduplicate calls to assignment operators of virtual bases are
8219 // made. As such, this exception specification is effectively unspecified.
8220 // Based on a similar decision made for constness in C++0x, we're erring on
8221 // the side of assuming such calls to be made regardless of whether they
8222 // actually happen.
8223 // Note that a move constructor is not implicitly declared when there are
8224 // virtual bases, but it can still be user-declared and explicitly defaulted.
8225 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8226 BaseEnd = ClassDecl->bases_end();
8227 Base != BaseEnd; ++Base) {
8228 if (Base->isVirtual())
8229 continue;
8230
8231 CXXRecordDecl *BaseClassDecl
8232 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8233 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8234 false, 0))
8235 ExceptSpec.CalledDecl(MoveAssign);
8236 }
8237
8238 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8239 BaseEnd = ClassDecl->vbases_end();
8240 Base != BaseEnd; ++Base) {
8241 CXXRecordDecl *BaseClassDecl
8242 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8243 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8244 false, 0))
8245 ExceptSpec.CalledDecl(MoveAssign);
8246 }
8247
8248 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8249 FieldEnd = ClassDecl->field_end();
8250 Field != FieldEnd;
8251 ++Field) {
8252 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8253 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8254 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8255 false, 0))
8256 ExceptSpec.CalledDecl(MoveAssign);
8257 }
8258 }
8259
8260 return ExceptSpec;
8261}
8262
8263CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8264 // Note: The following rules are largely analoguous to the move
8265 // constructor rules.
8266
8267 ImplicitExceptionSpecification Spec(
8268 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8269
8270 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8271 QualType RetType = Context.getLValueReferenceType(ArgType);
8272 ArgType = Context.getRValueReferenceType(ArgType);
8273
8274 // An implicitly-declared move assignment operator is an inline public
8275 // member of its class.
8276 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8277 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8278 SourceLocation ClassLoc = ClassDecl->getLocation();
8279 DeclarationNameInfo NameInfo(Name, ClassLoc);
8280 CXXMethodDecl *MoveAssignment
8281 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8282 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8283 /*TInfo=*/0, /*isStatic=*/false,
8284 /*StorageClassAsWritten=*/SC_None,
8285 /*isInline=*/true,
8286 /*isConstexpr=*/false,
8287 SourceLocation());
8288 MoveAssignment->setAccess(AS_public);
8289 MoveAssignment->setDefaulted();
8290 MoveAssignment->setImplicit();
8291 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8292
8293 // Add the parameter to the operator.
8294 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8295 ClassLoc, ClassLoc, /*Id=*/0,
8296 ArgType, /*TInfo=*/0,
8297 SC_None,
8298 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008299 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008300
8301 // Note that we have added this copy-assignment operator.
8302 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8303
8304 // C++0x [class.copy]p9:
8305 // If the definition of a class X does not explicitly declare a move
8306 // assignment operator, one will be implicitly declared as defaulted if and
8307 // only if:
8308 // [...]
8309 // - the move assignment operator would not be implicitly defined as
8310 // deleted.
8311 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8312 // Cache this result so that we don't try to generate this over and over
8313 // on every lookup, leaking memory and wasting time.
8314 ClassDecl->setFailedImplicitMoveAssignment();
8315 return 0;
8316 }
8317
8318 if (Scope *S = getScopeForContext(ClassDecl))
8319 PushOnScopeChains(MoveAssignment, S, false);
8320 ClassDecl->addDecl(MoveAssignment);
8321
8322 AddOverriddenMethods(ClassDecl, MoveAssignment);
8323 return MoveAssignment;
8324}
8325
8326void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8327 CXXMethodDecl *MoveAssignOperator) {
8328 assert((MoveAssignOperator->isDefaulted() &&
8329 MoveAssignOperator->isOverloadedOperator() &&
8330 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8331 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8332 "DefineImplicitMoveAssignment called for wrong function");
8333
8334 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8335
8336 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8337 MoveAssignOperator->setInvalidDecl();
8338 return;
8339 }
8340
8341 MoveAssignOperator->setUsed();
8342
8343 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8344 DiagnosticErrorTrap Trap(Diags);
8345
8346 // C++0x [class.copy]p28:
8347 // The implicitly-defined or move assignment operator for a non-union class
8348 // X performs memberwise move assignment of its subobjects. The direct base
8349 // classes of X are assigned first, in the order of their declaration in the
8350 // base-specifier-list, and then the immediate non-static data members of X
8351 // are assigned, in the order in which they were declared in the class
8352 // definition.
8353
8354 // The statements that form the synthesized function body.
8355 ASTOwningVector<Stmt*> Statements(*this);
8356
8357 // The parameter for the "other" object, which we are move from.
8358 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8359 QualType OtherRefType = Other->getType()->
8360 getAs<RValueReferenceType>()->getPointeeType();
8361 assert(OtherRefType.getQualifiers() == 0 &&
8362 "Bad argument type of defaulted move assignment");
8363
8364 // Our location for everything implicitly-generated.
8365 SourceLocation Loc = MoveAssignOperator->getLocation();
8366
8367 // Construct a reference to the "other" object. We'll be using this
8368 // throughout the generated ASTs.
8369 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8370 assert(OtherRef && "Reference to parameter cannot fail!");
8371 // Cast to rvalue.
8372 OtherRef = CastForMoving(*this, OtherRef);
8373
8374 // Construct the "this" pointer. We'll be using this throughout the generated
8375 // ASTs.
8376 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8377 assert(This && "Reference to this cannot fail!");
8378
8379 // Assign base classes.
8380 bool Invalid = false;
8381 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8382 E = ClassDecl->bases_end(); Base != E; ++Base) {
8383 // Form the assignment:
8384 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8385 QualType BaseType = Base->getType().getUnqualifiedType();
8386 if (!BaseType->isRecordType()) {
8387 Invalid = true;
8388 continue;
8389 }
8390
8391 CXXCastPath BasePath;
8392 BasePath.push_back(Base);
8393
8394 // Construct the "from" expression, which is an implicit cast to the
8395 // appropriately-qualified base type.
8396 Expr *From = OtherRef;
8397 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00008398 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00008399
8400 // Dereference "this".
8401 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8402
8403 // Implicitly cast "this" to the appropriately-qualified base type.
8404 To = ImpCastExprToType(To.take(),
8405 Context.getCVRQualifiedType(BaseType,
8406 MoveAssignOperator->getTypeQualifiers()),
8407 CK_UncheckedDerivedToBase,
8408 VK_LValue, &BasePath);
8409
8410 // Build the move.
8411 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8412 To.get(), From,
8413 /*CopyingBaseSubobject=*/true,
8414 /*Copying=*/false);
8415 if (Move.isInvalid()) {
8416 Diag(CurrentLocation, diag::note_member_synthesized_at)
8417 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8418 MoveAssignOperator->setInvalidDecl();
8419 return;
8420 }
8421
8422 // Success! Record the move.
8423 Statements.push_back(Move.takeAs<Expr>());
8424 }
8425
8426 // \brief Reference to the __builtin_memcpy function.
8427 Expr *BuiltinMemCpyRef = 0;
8428 // \brief Reference to the __builtin_objc_memmove_collectable function.
8429 Expr *CollectableMemCpyRef = 0;
8430
8431 // Assign non-static members.
8432 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8433 FieldEnd = ClassDecl->field_end();
8434 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008435 if (Field->isUnnamedBitfield())
8436 continue;
8437
Sebastian Redl22653ba2011-08-30 19:58:05 +00008438 // Check for members of reference type; we can't move those.
8439 if (Field->getType()->isReferenceType()) {
8440 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8441 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8442 Diag(Field->getLocation(), diag::note_declared_at);
8443 Diag(CurrentLocation, diag::note_member_synthesized_at)
8444 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8445 Invalid = true;
8446 continue;
8447 }
8448
8449 // Check for members of const-qualified, non-class type.
8450 QualType BaseType = Context.getBaseElementType(Field->getType());
8451 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8452 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8453 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8454 Diag(Field->getLocation(), diag::note_declared_at);
8455 Diag(CurrentLocation, diag::note_member_synthesized_at)
8456 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8457 Invalid = true;
8458 continue;
8459 }
8460
8461 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008462 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8463 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00008464
8465 QualType FieldType = Field->getType().getNonReferenceType();
8466 if (FieldType->isIncompleteArrayType()) {
8467 assert(ClassDecl->hasFlexibleArrayMember() &&
8468 "Incomplete array type is not valid");
8469 continue;
8470 }
8471
8472 // Build references to the field in the object we're copying from and to.
8473 CXXScopeSpec SS; // Intentionally empty
8474 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8475 LookupMemberName);
8476 MemberLookup.addDecl(*Field);
8477 MemberLookup.resolveKind();
8478 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8479 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008480 SS, SourceLocation(), 0,
8481 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008482 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8483 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008484 SS, SourceLocation(), 0,
8485 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008486 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8487 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8488
8489 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8490 "Member reference with rvalue base must be rvalue except for reference "
8491 "members, which aren't allowed for move assignment.");
8492
8493 // If the field should be copied with __builtin_memcpy rather than via
8494 // explicit assignments, do so. This optimization only applies for arrays
8495 // of scalars and arrays of class type with trivial move-assignment
8496 // operators.
8497 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8498 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8499 // Compute the size of the memory buffer to be copied.
8500 QualType SizeType = Context.getSizeType();
8501 llvm::APInt Size(Context.getTypeSize(SizeType),
8502 Context.getTypeSizeInChars(BaseType).getQuantity());
8503 for (const ConstantArrayType *Array
8504 = Context.getAsConstantArrayType(FieldType);
8505 Array;
8506 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8507 llvm::APInt ArraySize
8508 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8509 Size *= ArraySize;
8510 }
8511
Douglas Gregor528499b2011-09-01 02:09:07 +00008512 // Take the address of the field references for "from" and "to". We
8513 // directly construct UnaryOperators here because semantic analysis
8514 // does not permit us to take the address of an xvalue.
8515 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8516 Context.getPointerType(From.get()->getType()),
8517 VK_RValue, OK_Ordinary, Loc);
8518 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8519 Context.getPointerType(To.get()->getType()),
8520 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008521
8522 bool NeedsCollectableMemCpy =
8523 (BaseType->isRecordType() &&
8524 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8525
8526 if (NeedsCollectableMemCpy) {
8527 if (!CollectableMemCpyRef) {
8528 // Create a reference to the __builtin_objc_memmove_collectable function.
8529 LookupResult R(*this,
8530 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8531 Loc, LookupOrdinaryName);
8532 LookupName(R, TUScope, true);
8533
8534 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8535 if (!CollectableMemCpy) {
8536 // Something went horribly wrong earlier, and we will have
8537 // complained about it.
8538 Invalid = true;
8539 continue;
8540 }
8541
8542 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8543 CollectableMemCpy->getType(),
8544 VK_LValue, Loc, 0).take();
8545 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8546 }
8547 }
8548 // Create a reference to the __builtin_memcpy builtin function.
8549 else if (!BuiltinMemCpyRef) {
8550 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8551 LookupOrdinaryName);
8552 LookupName(R, TUScope, true);
8553
8554 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8555 if (!BuiltinMemCpy) {
8556 // Something went horribly wrong earlier, and we will have complained
8557 // about it.
8558 Invalid = true;
8559 continue;
8560 }
8561
8562 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8563 BuiltinMemCpy->getType(),
8564 VK_LValue, Loc, 0).take();
8565 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8566 }
8567
8568 ASTOwningVector<Expr*> CallArgs(*this);
8569 CallArgs.push_back(To.takeAs<Expr>());
8570 CallArgs.push_back(From.takeAs<Expr>());
8571 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8572 ExprResult Call = ExprError();
8573 if (NeedsCollectableMemCpy)
8574 Call = ActOnCallExpr(/*Scope=*/0,
8575 CollectableMemCpyRef,
8576 Loc, move_arg(CallArgs),
8577 Loc);
8578 else
8579 Call = ActOnCallExpr(/*Scope=*/0,
8580 BuiltinMemCpyRef,
8581 Loc, move_arg(CallArgs),
8582 Loc);
8583
8584 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8585 Statements.push_back(Call.takeAs<Expr>());
8586 continue;
8587 }
8588
8589 // Build the move of this field.
8590 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8591 To.get(), From.get(),
8592 /*CopyingBaseSubobject=*/false,
8593 /*Copying=*/false);
8594 if (Move.isInvalid()) {
8595 Diag(CurrentLocation, diag::note_member_synthesized_at)
8596 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8597 MoveAssignOperator->setInvalidDecl();
8598 return;
8599 }
8600
8601 // Success! Record the copy.
8602 Statements.push_back(Move.takeAs<Stmt>());
8603 }
8604
8605 if (!Invalid) {
8606 // Add a "return *this;"
8607 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8608
8609 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8610 if (Return.isInvalid())
8611 Invalid = true;
8612 else {
8613 Statements.push_back(Return.takeAs<Stmt>());
8614
8615 if (Trap.hasErrorOccurred()) {
8616 Diag(CurrentLocation, diag::note_member_synthesized_at)
8617 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8618 Invalid = true;
8619 }
8620 }
8621 }
8622
8623 if (Invalid) {
8624 MoveAssignOperator->setInvalidDecl();
8625 return;
8626 }
8627
8628 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8629 /*isStmtExpr=*/false);
8630 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8631 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8632
8633 if (ASTMutationListener *L = getASTMutationListener()) {
8634 L->CompletedImplicitDefinition(MoveAssignOperator);
8635 }
8636}
8637
Alexis Hunt913820d2011-05-13 06:10:58 +00008638std::pair<Sema::ImplicitExceptionSpecification, bool>
8639Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008640 if (ClassDecl->isInvalidDecl())
8641 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8642
Douglas Gregor54be3392010-07-01 17:57:27 +00008643 // C++ [class.copy]p5:
8644 // The implicitly-declared copy constructor for a class X will
8645 // have the form
8646 //
8647 // X::X(const X&)
8648 //
8649 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008650 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008651 bool HasConstCopyConstructor = true;
8652
8653 // -- each direct or virtual base class B of X has a copy
8654 // constructor whose first parameter is of type const B& or
8655 // const volatile B&, and
8656 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8657 BaseEnd = ClassDecl->bases_end();
8658 HasConstCopyConstructor && Base != BaseEnd;
8659 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008660 // Virtual bases are handled below.
8661 if (Base->isVirtual())
8662 continue;
8663
Douglas Gregora6d69502010-07-02 23:41:54 +00008664 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008665 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008666 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8667 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008668 }
8669
8670 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8671 BaseEnd = ClassDecl->vbases_end();
8672 HasConstCopyConstructor && Base != BaseEnd;
8673 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008674 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008675 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008676 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8677 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008678 }
8679
8680 // -- for all the nonstatic data members of X that are of a
8681 // class type M (or array thereof), each such class type
8682 // has a copy constructor whose first parameter is of type
8683 // const M& or const volatile M&.
8684 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8685 FieldEnd = ClassDecl->field_end();
8686 HasConstCopyConstructor && Field != FieldEnd;
8687 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008688 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008689 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008690 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8691 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008692 }
8693 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008694 // Otherwise, the implicitly declared copy constructor will have
8695 // the form
8696 //
8697 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008698
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008699 // C++ [except.spec]p14:
8700 // An implicitly declared special member function (Clause 12) shall have an
8701 // exception-specification. [...]
8702 ImplicitExceptionSpecification ExceptSpec(Context);
8703 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8704 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8705 BaseEnd = ClassDecl->bases_end();
8706 Base != BaseEnd;
8707 ++Base) {
8708 // Virtual bases are handled below.
8709 if (Base->isVirtual())
8710 continue;
8711
Douglas Gregora6d69502010-07-02 23:41:54 +00008712 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008713 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008714 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008715 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008716 ExceptSpec.CalledDecl(CopyConstructor);
8717 }
8718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8719 BaseEnd = ClassDecl->vbases_end();
8720 Base != BaseEnd;
8721 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008722 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008723 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008724 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008725 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008726 ExceptSpec.CalledDecl(CopyConstructor);
8727 }
8728 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8729 FieldEnd = ClassDecl->field_end();
8730 Field != FieldEnd;
8731 ++Field) {
8732 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008733 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8734 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008735 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008736 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008737 }
8738 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008739
Alexis Hunt913820d2011-05-13 06:10:58 +00008740 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8741}
8742
8743CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8744 CXXRecordDecl *ClassDecl) {
8745 // C++ [class.copy]p4:
8746 // If the class definition does not explicitly declare a copy
8747 // constructor, one is declared implicitly.
8748
8749 ImplicitExceptionSpecification Spec(Context);
8750 bool Const;
8751 llvm::tie(Spec, Const) =
8752 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8753
8754 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8755 QualType ArgType = ClassType;
8756 if (Const)
8757 ArgType = ArgType.withConst();
8758 ArgType = Context.getLValueReferenceType(ArgType);
8759
8760 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8761
Douglas Gregor54be3392010-07-01 17:57:27 +00008762 DeclarationName Name
8763 = Context.DeclarationNames.getCXXConstructorName(
8764 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008765 SourceLocation ClassLoc = ClassDecl->getLocation();
8766 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008767
8768 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008769 // member of its class.
8770 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8771 Context, ClassDecl, ClassLoc, NameInfo,
8772 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8773 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8774 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8775 getLangOptions().CPlusPlus0x);
Douglas Gregor54be3392010-07-01 17:57:27 +00008776 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008777 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008778 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008779
Douglas Gregora6d69502010-07-02 23:41:54 +00008780 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008781 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8782
Douglas Gregor54be3392010-07-01 17:57:27 +00008783 // Add the parameter to the constructor.
8784 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008785 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008786 /*IdentifierInfo=*/0,
8787 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008788 SC_None,
8789 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008790 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008791
Douglas Gregor0be31a22010-07-02 17:43:08 +00008792 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008793 PushOnScopeChains(CopyConstructor, S, false);
8794 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008795
Nico Weber94e746d2012-01-23 03:19:29 +00008796 // C++11 [class.copy]p8:
8797 // ... If the class definition does not explicitly declare a copy
8798 // constructor, there is no user-declared move constructor, and there is no
8799 // user-declared move assignment operator, a copy constructor is implicitly
8800 // declared as defaulted.
Alexis Huntd74c85f2011-06-22 01:05:13 +00008801 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weber94e746d2012-01-23 03:19:29 +00008802 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber323076f2012-01-23 04:01:33 +00008803 !getLangOptions().MicrosoftMode) ||
Alexis Hunt1bc6f712011-10-11 04:55:36 +00008804 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008805 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008806
8807 return CopyConstructor;
8808}
8809
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008810void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008811 CXXConstructorDecl *CopyConstructor) {
8812 assert((CopyConstructor->isDefaulted() &&
8813 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008814 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008815 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008816
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008817 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008818 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008819
Douglas Gregora57478e2010-05-01 15:04:51 +00008820 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008821 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008822
Alexis Hunt1d792652011-01-08 20:30:50 +00008823 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008824 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008825 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008826 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008827 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008828 } else {
8829 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8830 CopyConstructor->getLocation(),
8831 MultiStmtArg(*this, 0, 0),
8832 /*isStmtExpr=*/false)
8833 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008834 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008835 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008836
8837 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008838 if (ASTMutationListener *L = getASTMutationListener()) {
8839 L->CompletedImplicitDefinition(CopyConstructor);
8840 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008841}
8842
Sebastian Redl22653ba2011-08-30 19:58:05 +00008843Sema::ImplicitExceptionSpecification
8844Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8845 // C++ [except.spec]p14:
8846 // An implicitly declared special member function (Clause 12) shall have an
8847 // exception-specification. [...]
8848 ImplicitExceptionSpecification ExceptSpec(Context);
8849 if (ClassDecl->isInvalidDecl())
8850 return ExceptSpec;
8851
8852 // Direct base-class constructors.
8853 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8854 BEnd = ClassDecl->bases_end();
8855 B != BEnd; ++B) {
8856 if (B->isVirtual()) // Handled below.
8857 continue;
8858
8859 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8860 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8861 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8862 // If this is a deleted function, add it anyway. This might be conformant
8863 // with the standard. This might not. I'm not sure. It might not matter.
8864 if (Constructor)
8865 ExceptSpec.CalledDecl(Constructor);
8866 }
8867 }
8868
8869 // Virtual base-class constructors.
8870 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8871 BEnd = ClassDecl->vbases_end();
8872 B != BEnd; ++B) {
8873 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8874 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8875 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8876 // If this is a deleted function, add it anyway. This might be conformant
8877 // with the standard. This might not. I'm not sure. It might not matter.
8878 if (Constructor)
8879 ExceptSpec.CalledDecl(Constructor);
8880 }
8881 }
8882
8883 // Field constructors.
8884 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8885 FEnd = ClassDecl->field_end();
8886 F != FEnd; ++F) {
Douglas Gregor7db3e952011-11-28 20:03:15 +00008887 if (const RecordType *RecordTy
Sebastian Redl22653ba2011-08-30 19:58:05 +00008888 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8889 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8890 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8891 // If this is a deleted function, add it anyway. This might be conformant
8892 // with the standard. This might not. I'm not sure. It might not matter.
8893 // In particular, the problem is that this function never gets called. It
8894 // might just be ill-formed because this function attempts to refer to
8895 // a deleted function here.
8896 if (Constructor)
8897 ExceptSpec.CalledDecl(Constructor);
8898 }
8899 }
8900
8901 return ExceptSpec;
8902}
8903
8904CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8905 CXXRecordDecl *ClassDecl) {
8906 ImplicitExceptionSpecification Spec(
8907 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8908
8909 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8910 QualType ArgType = Context.getRValueReferenceType(ClassType);
8911
8912 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8913
8914 DeclarationName Name
8915 = Context.DeclarationNames.getCXXConstructorName(
8916 Context.getCanonicalType(ClassType));
8917 SourceLocation ClassLoc = ClassDecl->getLocation();
8918 DeclarationNameInfo NameInfo(Name, ClassLoc);
8919
8920 // C++0x [class.copy]p11:
8921 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008922 // member of its class.
8923 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8924 Context, ClassDecl, ClassLoc, NameInfo,
8925 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8926 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8927 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8928 getLangOptions().CPlusPlus0x);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008929 MoveConstructor->setAccess(AS_public);
8930 MoveConstructor->setDefaulted();
8931 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008932
Sebastian Redl22653ba2011-08-30 19:58:05 +00008933 // Add the parameter to the constructor.
8934 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8935 ClassLoc, ClassLoc,
8936 /*IdentifierInfo=*/0,
8937 ArgType, /*TInfo=*/0,
8938 SC_None,
8939 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008940 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008941
8942 // C++0x [class.copy]p9:
8943 // If the definition of a class X does not explicitly declare a move
8944 // constructor, one will be implicitly declared as defaulted if and only if:
8945 // [...]
8946 // - the move constructor would not be implicitly defined as deleted.
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00008947 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00008948 // Cache this result so that we don't try to generate this over and over
8949 // on every lookup, leaking memory and wasting time.
8950 ClassDecl->setFailedImplicitMoveConstructor();
8951 return 0;
8952 }
8953
8954 // Note that we have declared this constructor.
8955 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8956
8957 if (Scope *S = getScopeForContext(ClassDecl))
8958 PushOnScopeChains(MoveConstructor, S, false);
8959 ClassDecl->addDecl(MoveConstructor);
8960
8961 return MoveConstructor;
8962}
8963
8964void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8965 CXXConstructorDecl *MoveConstructor) {
8966 assert((MoveConstructor->isDefaulted() &&
8967 MoveConstructor->isMoveConstructor() &&
8968 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8969 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8970
8971 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8972 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8973
8974 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8975 DiagnosticErrorTrap Trap(Diags);
8976
8977 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8978 Trap.hasErrorOccurred()) {
8979 Diag(CurrentLocation, diag::note_member_synthesized_at)
8980 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8981 MoveConstructor->setInvalidDecl();
8982 } else {
8983 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8984 MoveConstructor->getLocation(),
8985 MultiStmtArg(*this, 0, 0),
8986 /*isStmtExpr=*/false)
8987 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008988 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008989 }
8990
8991 MoveConstructor->setUsed();
8992
8993 if (ASTMutationListener *L = getASTMutationListener()) {
8994 L->CompletedImplicitDefinition(MoveConstructor);
8995 }
8996}
8997
John McCalldadc5752010-08-24 06:29:42 +00008998ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008999Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00009000 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00009001 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009002 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009003 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009004 unsigned ConstructKind,
9005 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00009006 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00009007
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009008 // C++0x [class.copy]p34:
9009 // When certain criteria are met, an implementation is allowed to
9010 // omit the copy/move construction of a class object, even if the
9011 // copy/move constructor and/or destructor for the object have
9012 // side effects. [...]
9013 // - when a temporary class object that has not been bound to a
9014 // reference (12.2) would be copied/moved to a class object
9015 // with the same cv-unqualified type, the copy/move operation
9016 // can be omitted by constructing the temporary object
9017 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00009018 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00009019 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009020 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00009021 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00009022 }
Mike Stump11289f42009-09-09 15:08:12 +00009023
9024 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009025 Elidable, move(ExprArgs), HadMultipleCandidates,
9026 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00009027}
9028
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009029/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9030/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00009031ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00009032Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9033 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00009034 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009035 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009036 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009037 unsigned ConstructKind,
9038 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00009039 unsigned NumExprs = ExprArgs.size();
9040 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00009041
Nick Lewyckyd4693212011-03-25 01:44:32 +00009042 for (specific_attr_iterator<NonNullAttr>
9043 i = Constructor->specific_attr_begin<NonNullAttr>(),
9044 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9045 const NonNullAttr *NonNull = *i;
9046 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9047 }
9048
Eli Friedmanfa0df832012-02-02 03:46:19 +00009049 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00009050 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009051 Constructor, Elidable, Exprs, NumExprs,
9052 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009053 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9054 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009055}
9056
Mike Stump11289f42009-09-09 15:08:12 +00009057bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009058 CXXConstructorDecl *Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009059 MultiExprArg Exprs,
9060 bool HadMultipleCandidates) {
Chandler Carruth01718152010-10-25 08:47:36 +00009061 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00009062 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00009063 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009064 move(Exprs), HadMultipleCandidates, false,
9065 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009066 if (TempResult.isInvalid())
9067 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009068
Anders Carlsson6eb55572009-08-25 05:12:04 +00009069 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00009070 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009071 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00009072 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00009073 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00009074
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009075 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00009076}
9077
John McCall03c48482010-02-02 09:10:11 +00009078void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00009079 if (VD->isInvalidDecl()) return;
9080
John McCall03c48482010-02-02 09:10:11 +00009081 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00009082 if (ClassDecl->isInvalidDecl()) return;
9083 if (ClassDecl->hasTrivialDestructor()) return;
9084 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00009085
Chandler Carruth86d17d32011-03-27 21:26:48 +00009086 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009087 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +00009088 CheckDestructorAccess(VD->getLocation(), Destructor,
9089 PDiag(diag::err_access_dtor_var)
9090 << VD->getDeclName()
9091 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00009092
Chandler Carruth86d17d32011-03-27 21:26:48 +00009093 if (!VD->hasGlobalStorage()) return;
9094
9095 // Emit warning for non-trivial dtor in global scope (a real global,
9096 // class-static, function-static).
9097 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9098
9099 // TODO: this should be re-enabled for static locals by !CXAAtExit
9100 if (!VD->isStaticLocal())
9101 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009102}
9103
Mike Stump11289f42009-09-09 15:08:12 +00009104/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009105/// ActOnDeclarator, when a C++ direct initializer is present.
9106/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00009107void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00009108 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009109 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00009110 SourceLocation RParenLoc,
9111 bool TypeMayContainAuto) {
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009112 // If there is no declaration, there was an error parsing it. Just ignore
9113 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00009114 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009115 return;
Mike Stump11289f42009-09-09 15:08:12 +00009116
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009117 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9118 if (!VDecl) {
9119 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9120 RealDecl->setInvalidDecl();
9121 return;
9122 }
9123
Eli Friedmande30e522012-01-05 22:34:08 +00009124 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith30482bc2011-02-20 03:19:35 +00009125 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedmande30e522012-01-05 22:34:08 +00009126 if (Exprs.size() == 0) {
9127 // It isn't possible to write this directly, but it is possible to
9128 // end up in this situation with "auto x(some_pack...);"
9129 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9130 << VDecl->getDeclName() << VDecl->getType()
9131 << VDecl->getSourceRange();
9132 RealDecl->setInvalidDecl();
9133 return;
9134 }
9135
Richard Smith30482bc2011-02-20 03:19:35 +00009136 if (Exprs.size() > 1) {
9137 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9138 diag::err_auto_var_init_multiple_expressions)
9139 << VDecl->getDeclName() << VDecl->getType()
9140 << VDecl->getSourceRange();
9141 RealDecl->setInvalidDecl();
9142 return;
9143 }
9144
9145 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00009146 TypeSourceInfo *DeducedType = 0;
Sebastian Redl09edce02012-01-23 22:09:39 +00009147 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9148 DAR_Failed)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00009149 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smith9647d3c2011-03-17 16:11:59 +00009150 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00009151 RealDecl->setInvalidDecl();
9152 return;
9153 }
Richard Smith9647d3c2011-03-17 16:11:59 +00009154 VDecl->setTypeSourceInfo(DeducedType);
9155 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00009156
John McCall31168b02011-06-15 23:02:42 +00009157 // In ARC, infer lifetime.
9158 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9159 VDecl->setInvalidDecl();
9160
Richard Smith30482bc2011-02-20 03:19:35 +00009161 // If this is a redeclaration, check that the type we just deduced matches
9162 // the previously declared type.
Douglas Gregorec9fd132012-01-14 16:38:05 +00009163 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith30482bc2011-02-20 03:19:35 +00009164 MergeVarDeclTypes(VDecl, Old);
9165 }
9166
Douglas Gregor402250f2009-08-26 21:14:46 +00009167 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009168 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009169 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9170 //
9171 // Clients that want to distinguish between the two forms, can check for
9172 // direct initializer using VarDecl::hasCXXDirectInitializer().
9173 // A major benefit is that clients that don't particularly care about which
9174 // exactly form was it (like the CodeGen) can handle both cases without
9175 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009176
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009177 // C++ 8.5p11:
9178 // The form of initialization (using parentheses or '=') is generally
9179 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009180 // class type.
9181
Douglas Gregor50dc2192010-02-11 22:55:30 +00009182 if (!VDecl->getType()->isDependentType() &&
Douglas Gregorb06fa542011-10-10 16:05:18 +00009183 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor50dc2192010-02-11 22:55:30 +00009184 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00009185 diag::err_typecheck_decl_incomplete_type)) {
9186 VDecl->setInvalidDecl();
9187 return;
9188 }
9189
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009190 // The variable can not have an abstract class type.
9191 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9192 diag::err_abstract_type_in_decl,
9193 AbstractVariableType))
9194 VDecl->setInvalidDecl();
9195
Sebastian Redl5ca79842010-02-01 20:16:42 +00009196 const VarDecl *Def;
9197 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009198 Diag(VDecl->getLocation(), diag::err_redefinition)
9199 << VDecl->getDeclName();
9200 Diag(Def->getLocation(), diag::note_previous_definition);
9201 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009202 return;
9203 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00009204
Douglas Gregorf0f83692010-08-24 05:27:49 +00009205 // C++ [class.static.data]p4
9206 // If a static data member is of const integral or const
9207 // enumeration type, its declaration in the class definition can
9208 // specify a constant-initializer which shall be an integral
9209 // constant expression (5.19). In that case, the member can appear
9210 // in integral constant expressions. The member shall still be
9211 // defined in a namespace scope if it is used in the program and the
9212 // namespace scope definition shall not contain an initializer.
9213 //
9214 // We already performed a redefinition check above, but for static
9215 // data members we also need to check whether there was an in-class
9216 // declaration with an initializer.
9217 const VarDecl* PrevInit = 0;
9218 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9219 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9220 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9221 return;
9222 }
9223
Douglas Gregor71f39c92010-12-16 01:31:22 +00009224 bool IsDependent = false;
9225 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9226 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9227 VDecl->setInvalidDecl();
9228 return;
9229 }
9230
9231 if (Exprs.get()[I]->isTypeDependent())
9232 IsDependent = true;
9233 }
9234
Douglas Gregor50dc2192010-02-11 22:55:30 +00009235 // If either the declaration has a dependent type or if any of the
9236 // expressions is type-dependent, we represent the initialization
9237 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00009238 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00009239 // Let clients know that initialization was done with a direct initializer.
9240 VDecl->setCXXDirectInitializer(true);
9241
9242 // Store the initialization expressions as a ParenListExpr.
9243 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00009244 VDecl->setInit(new (Context) ParenListExpr(
9245 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9246 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00009247 return;
9248 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009249
9250 // Capture the variable that is being initialized and the style of
9251 // initialization.
9252 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9253
9254 // FIXME: Poor source location information.
9255 InitializationKind Kind
9256 = InitializationKind::CreateDirect(VDecl->getLocation(),
9257 LParenLoc, RParenLoc);
9258
Douglas Gregorb06fa542011-10-10 16:05:18 +00009259 QualType T = VDecl->getType();
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009260 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00009261 Exprs.get(), Exprs.size());
Douglas Gregorb06fa542011-10-10 16:05:18 +00009262 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009263 if (Result.isInvalid()) {
9264 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009265 return;
Douglas Gregorb06fa542011-10-10 16:05:18 +00009266 } else if (T != VDecl->getType()) {
9267 VDecl->setType(T);
9268 Result.get()->setType(T);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009269 }
John McCallacf0ee52010-10-08 02:01:28 +00009270
Douglas Gregorb06fa542011-10-10 16:05:18 +00009271
Richard Smith2316cd82011-09-29 19:11:37 +00009272 Expr *Init = Result.get();
9273 CheckImplicitConversions(Init, LParenLoc);
Richard Smith2316cd82011-09-29 19:11:37 +00009274
9275 Init = MaybeCreateExprWithCleanups(Init);
9276 VDecl->setInit(Init);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009277 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009278
John McCall8b7fd8f12011-01-19 11:48:09 +00009279 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009280}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009281
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009282/// \brief Given a constructor and the set of arguments provided for the
9283/// constructor, convert the arguments and add any required default arguments
9284/// to form a proper call to this constructor.
9285///
9286/// \returns true if an error occurred, false otherwise.
9287bool
9288Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9289 MultiExprArg ArgsPtr,
9290 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00009291 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009292 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9293 unsigned NumArgs = ArgsPtr.size();
9294 Expr **Args = (Expr **)ArgsPtr.get();
9295
9296 const FunctionProtoType *Proto
9297 = Constructor->getType()->getAs<FunctionProtoType>();
9298 assert(Proto && "Constructor without a prototype?");
9299 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009300
9301 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009302 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009303 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009304 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009305 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009306
9307 VariadicCallType CallType =
9308 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009309 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009310 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9311 Proto, 0, Args, NumArgs, AllArgs,
9312 CallType);
9313 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9314 ConvertedArgs.push_back(AllArgs[i]);
9315 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009316}
9317
Anders Carlssone363c8e2009-12-12 00:32:00 +00009318static inline bool
9319CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9320 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009321 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00009322 if (isa<NamespaceDecl>(DC)) {
9323 return SemaRef.Diag(FnDecl->getLocation(),
9324 diag::err_operator_new_delete_declared_in_namespace)
9325 << FnDecl->getDeclName();
9326 }
9327
9328 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00009329 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009330 return SemaRef.Diag(FnDecl->getLocation(),
9331 diag::err_operator_new_delete_declared_static)
9332 << FnDecl->getDeclName();
9333 }
9334
Anders Carlsson60659a82009-12-12 02:43:16 +00009335 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00009336}
9337
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009338static inline bool
9339CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9340 CanQualType ExpectedResultType,
9341 CanQualType ExpectedFirstParamType,
9342 unsigned DependentParamTypeDiag,
9343 unsigned InvalidParamTypeDiag) {
9344 QualType ResultType =
9345 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9346
9347 // Check that the result type is not dependent.
9348 if (ResultType->isDependentType())
9349 return SemaRef.Diag(FnDecl->getLocation(),
9350 diag::err_operator_new_delete_dependent_result_type)
9351 << FnDecl->getDeclName() << ExpectedResultType;
9352
9353 // Check that the result type is what we expect.
9354 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9355 return SemaRef.Diag(FnDecl->getLocation(),
9356 diag::err_operator_new_delete_invalid_result_type)
9357 << FnDecl->getDeclName() << ExpectedResultType;
9358
9359 // A function template must have at least 2 parameters.
9360 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9361 return SemaRef.Diag(FnDecl->getLocation(),
9362 diag::err_operator_new_delete_template_too_few_parameters)
9363 << FnDecl->getDeclName();
9364
9365 // The function decl must have at least 1 parameter.
9366 if (FnDecl->getNumParams() == 0)
9367 return SemaRef.Diag(FnDecl->getLocation(),
9368 diag::err_operator_new_delete_too_few_parameters)
9369 << FnDecl->getDeclName();
9370
9371 // Check the the first parameter type is not dependent.
9372 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9373 if (FirstParamType->isDependentType())
9374 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9375 << FnDecl->getDeclName() << ExpectedFirstParamType;
9376
9377 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00009378 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009379 ExpectedFirstParamType)
9380 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9381 << FnDecl->getDeclName() << ExpectedFirstParamType;
9382
9383 return false;
9384}
9385
Anders Carlsson12308f42009-12-11 23:23:22 +00009386static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009387CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009388 // C++ [basic.stc.dynamic.allocation]p1:
9389 // A program is ill-formed if an allocation function is declared in a
9390 // namespace scope other than global scope or declared static in global
9391 // scope.
9392 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9393 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009394
9395 CanQualType SizeTy =
9396 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9397
9398 // C++ [basic.stc.dynamic.allocation]p1:
9399 // The return type shall be void*. The first parameter shall have type
9400 // std::size_t.
9401 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9402 SizeTy,
9403 diag::err_operator_new_dependent_param_type,
9404 diag::err_operator_new_param_type))
9405 return true;
9406
9407 // C++ [basic.stc.dynamic.allocation]p1:
9408 // The first parameter shall not have an associated default argument.
9409 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00009410 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009411 diag::err_operator_new_default_arg)
9412 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9413
9414 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00009415}
9416
9417static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00009418CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9419 // C++ [basic.stc.dynamic.deallocation]p1:
9420 // A program is ill-formed if deallocation functions are declared in a
9421 // namespace scope other than global scope or declared static in global
9422 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00009423 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9424 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009425
9426 // C++ [basic.stc.dynamic.deallocation]p2:
9427 // Each deallocation function shall return void and its first parameter
9428 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009429 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9430 SemaRef.Context.VoidPtrTy,
9431 diag::err_operator_delete_dependent_param_type,
9432 diag::err_operator_delete_param_type))
9433 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009434
Anders Carlsson12308f42009-12-11 23:23:22 +00009435 return false;
9436}
9437
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009438/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9439/// of this overloaded operator is well-formed. If so, returns false;
9440/// otherwise, emits appropriate diagnostics and returns true.
9441bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00009442 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009443 "Expected an overloaded operator declaration");
9444
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009445 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9446
Mike Stump11289f42009-09-09 15:08:12 +00009447 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009448 // The allocation and deallocation functions, operator new,
9449 // operator new[], operator delete and operator delete[], are
9450 // described completely in 3.7.3. The attributes and restrictions
9451 // found in the rest of this subclause do not apply to them unless
9452 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00009453 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00009454 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00009455
Anders Carlsson22f443f2009-12-12 00:26:23 +00009456 if (Op == OO_New || Op == OO_Array_New)
9457 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009458
9459 // C++ [over.oper]p6:
9460 // An operator function shall either be a non-static member
9461 // function or be a non-member function and have at least one
9462 // parameter whose type is a class, a reference to a class, an
9463 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00009464 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9465 if (MethodDecl->isStatic())
9466 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009467 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009468 } else {
9469 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00009470 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9471 ParamEnd = FnDecl->param_end();
9472 Param != ParamEnd; ++Param) {
9473 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00009474 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9475 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009476 ClassOrEnumParam = true;
9477 break;
9478 }
9479 }
9480
Douglas Gregord69246b2008-11-17 16:14:12 +00009481 if (!ClassOrEnumParam)
9482 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009483 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009484 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009485 }
9486
9487 // C++ [over.oper]p8:
9488 // An operator function cannot have default arguments (8.3.6),
9489 // except where explicitly stated below.
9490 //
Mike Stump11289f42009-09-09 15:08:12 +00009491 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009492 // (C++ [over.call]p1).
9493 if (Op != OO_Call) {
9494 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9495 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009496 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00009497 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00009498 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009499 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009500 }
9501 }
9502
Douglas Gregor6cf08062008-11-10 13:38:07 +00009503 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9504 { false, false, false }
9505#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9506 , { Unary, Binary, MemberOnly }
9507#include "clang/Basic/OperatorKinds.def"
9508 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009509
Douglas Gregor6cf08062008-11-10 13:38:07 +00009510 bool CanBeUnaryOperator = OperatorUses[Op][0];
9511 bool CanBeBinaryOperator = OperatorUses[Op][1];
9512 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009513
9514 // C++ [over.oper]p8:
9515 // [...] Operator functions cannot have more or fewer parameters
9516 // than the number required for the corresponding operator, as
9517 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00009518 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00009519 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009520 if (Op != OO_Call &&
9521 ((NumParams == 1 && !CanBeUnaryOperator) ||
9522 (NumParams == 2 && !CanBeBinaryOperator) ||
9523 (NumParams < 1) || (NumParams > 2))) {
9524 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009525 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00009526 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009527 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00009528 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009529 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009530 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00009531 assert(CanBeBinaryOperator &&
9532 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009533 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009534 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009535
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009536 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009537 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009538 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009539
Douglas Gregord69246b2008-11-17 16:14:12 +00009540 // Overloaded operators other than operator() cannot be variadic.
9541 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009542 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009543 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009544 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009545 }
9546
9547 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009548 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9549 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009550 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009551 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009552 }
9553
9554 // C++ [over.inc]p1:
9555 // The user-defined function called operator++ implements the
9556 // prefix and postfix ++ operator. If this function is a member
9557 // function with no parameters, or a non-member function with one
9558 // parameter of class or enumeration type, it defines the prefix
9559 // increment operator ++ for objects of that type. If the function
9560 // is a member function with one parameter (which shall be of type
9561 // int) or a non-member function with two parameters (the second
9562 // of which shall be of type int), it defines the postfix
9563 // increment operator ++ for objects of that type.
9564 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9565 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9566 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009567 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009568 ParamIsInt = BT->getKind() == BuiltinType::Int;
9569
Chris Lattner2b786902008-11-21 07:50:02 +00009570 if (!ParamIsInt)
9571 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009572 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009573 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009574 }
9575
Douglas Gregord69246b2008-11-17 16:14:12 +00009576 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009577}
Chris Lattner3b024a32008-12-17 07:09:26 +00009578
Alexis Huntc88db062010-01-13 09:01:02 +00009579/// CheckLiteralOperatorDeclaration - Check whether the declaration
9580/// of this literal operator function is well-formed. If so, returns
9581/// false; otherwise, emits appropriate diagnostics and returns true.
9582bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9583 DeclContext *DC = FnDecl->getDeclContext();
9584 Decl::Kind Kind = DC->getDeclKind();
9585 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9586 Kind != Decl::LinkageSpec) {
9587 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9588 << FnDecl->getDeclName();
9589 return true;
9590 }
9591
9592 bool Valid = false;
9593
Alexis Hunt7dd26172010-04-07 23:11:06 +00009594 // template <char...> type operator "" name() is the only valid template
9595 // signature, and the only valid signature with no parameters.
9596 if (FnDecl->param_size() == 0) {
9597 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9598 // Must have only one template parameter
9599 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9600 if (Params->size() == 1) {
9601 NonTypeTemplateParmDecl *PmDecl =
9602 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009603
Alexis Hunt7dd26172010-04-07 23:11:06 +00009604 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009605 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9606 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9607 Valid = true;
9608 }
9609 }
9610 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009611 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009612 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9613
Alexis Huntc88db062010-01-13 09:01:02 +00009614 QualType T = (*Param)->getType();
9615
Alexis Hunt079a6f72010-04-07 22:57:35 +00009616 // unsigned long long int, long double, and any character type are allowed
9617 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009618 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9619 Context.hasSameType(T, Context.LongDoubleTy) ||
9620 Context.hasSameType(T, Context.CharTy) ||
9621 Context.hasSameType(T, Context.WCharTy) ||
9622 Context.hasSameType(T, Context.Char16Ty) ||
9623 Context.hasSameType(T, Context.Char32Ty)) {
9624 if (++Param == FnDecl->param_end())
9625 Valid = true;
9626 goto FinishedParams;
9627 }
9628
Alexis Hunt079a6f72010-04-07 22:57:35 +00009629 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009630 const PointerType *PT = T->getAs<PointerType>();
9631 if (!PT)
9632 goto FinishedParams;
9633 T = PT->getPointeeType();
9634 if (!T.isConstQualified())
9635 goto FinishedParams;
9636 T = T.getUnqualifiedType();
9637
9638 // Move on to the second parameter;
9639 ++Param;
9640
9641 // If there is no second parameter, the first must be a const char *
9642 if (Param == FnDecl->param_end()) {
9643 if (Context.hasSameType(T, Context.CharTy))
9644 Valid = true;
9645 goto FinishedParams;
9646 }
9647
9648 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9649 // are allowed as the first parameter to a two-parameter function
9650 if (!(Context.hasSameType(T, Context.CharTy) ||
9651 Context.hasSameType(T, Context.WCharTy) ||
9652 Context.hasSameType(T, Context.Char16Ty) ||
9653 Context.hasSameType(T, Context.Char32Ty)))
9654 goto FinishedParams;
9655
9656 // The second and final parameter must be an std::size_t
9657 T = (*Param)->getType().getUnqualifiedType();
9658 if (Context.hasSameType(T, Context.getSizeType()) &&
9659 ++Param == FnDecl->param_end())
9660 Valid = true;
9661 }
9662
9663 // FIXME: This diagnostic is absolutely terrible.
9664FinishedParams:
9665 if (!Valid) {
9666 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9667 << FnDecl->getDeclName();
9668 return true;
9669 }
9670
Douglas Gregor86325ad2011-08-30 22:40:35 +00009671 StringRef LiteralName
9672 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9673 if (LiteralName[0] != '_') {
9674 // C++0x [usrlit.suffix]p1:
9675 // Literal suffix identifiers that do not start with an underscore are
9676 // reserved for future standardization.
9677 bool IsHexFloat = true;
9678 if (LiteralName.size() > 1 &&
9679 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9680 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9681 if (!isdigit(LiteralName[I])) {
9682 IsHexFloat = false;
9683 break;
9684 }
9685 }
9686 }
9687
9688 if (IsHexFloat)
9689 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9690 << LiteralName;
9691 else
9692 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9693 }
9694
Alexis Huntc88db062010-01-13 09:01:02 +00009695 return false;
9696}
9697
Douglas Gregor07665a62009-01-05 19:45:36 +00009698/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9699/// linkage specification, including the language and (if present)
9700/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9701/// the location of the language string literal, which is provided
9702/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9703/// the '{' brace. Otherwise, this linkage specification does not
9704/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009705Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9706 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009707 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009708 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009709 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009710 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009711 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009712 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009713 Language = LinkageSpecDecl::lang_cxx;
9714 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009715 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009716 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009717 }
Mike Stump11289f42009-09-09 15:08:12 +00009718
Chris Lattner438e5012008-12-17 07:13:27 +00009719 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009720
Douglas Gregor07665a62009-01-05 19:45:36 +00009721 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009722 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009723 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009724 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009725 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009726}
9727
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009728/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009729/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9730/// valid, it's the position of the closing '}' brace in a linkage
9731/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009732Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009733 Decl *LinkageSpec,
9734 SourceLocation RBraceLoc) {
9735 if (LinkageSpec) {
9736 if (RBraceLoc.isValid()) {
9737 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9738 LSDecl->setRBraceLoc(RBraceLoc);
9739 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009740 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009741 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009742 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009743}
9744
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009745/// \brief Perform semantic analysis for the variable declaration that
9746/// occurs within a C++ catch clause, returning the newly-created
9747/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009748VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009749 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009750 SourceLocation StartLoc,
9751 SourceLocation Loc,
9752 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009753 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009754 QualType ExDeclType = TInfo->getType();
9755
Sebastian Redl54c04d42008-12-22 19:15:10 +00009756 // Arrays and functions decay.
9757 if (ExDeclType->isArrayType())
9758 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9759 else if (ExDeclType->isFunctionType())
9760 ExDeclType = Context.getPointerType(ExDeclType);
9761
9762 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9763 // The exception-declaration shall not denote a pointer or reference to an
9764 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009765 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009766 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009767 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009768 Invalid = true;
9769 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009770
Sebastian Redl54c04d42008-12-22 19:15:10 +00009771 QualType BaseType = ExDeclType;
9772 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009773 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009774 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009775 BaseType = Ptr->getPointeeType();
9776 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009777 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00009778 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009779 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009780 BaseType = Ref->getPointeeType();
9781 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009782 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009783 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009784 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009785 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00009786 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009787
Mike Stump11289f42009-09-09 15:08:12 +00009788 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009789 RequireNonAbstractType(Loc, ExDeclType,
9790 diag::err_abstract_type_in_decl,
9791 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009792 Invalid = true;
9793
John McCall2ca705e2010-07-24 00:37:23 +00009794 // Only the non-fragile NeXT runtime currently supports C++ catches
9795 // of ObjC types, and no runtime supports catching ObjC types by value.
9796 if (!Invalid && getLangOptions().ObjC1) {
9797 QualType T = ExDeclType;
9798 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9799 T = RT->getPointeeType();
9800
9801 if (T->isObjCObjectType()) {
9802 Diag(Loc, diag::err_objc_object_catch);
9803 Invalid = true;
9804 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009805 if (!getLangOptions().ObjCNonFragileABI)
9806 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009807 }
9808 }
9809
Abramo Bagnaradff19302011-03-08 08:55:46 +00009810 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9811 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009812 ExDecl->setExceptionVariable(true);
9813
Douglas Gregor8ca0c642011-12-10 01:22:52 +00009814 // In ARC, infer 'retaining' for variables of retainable type.
9815 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9816 Invalid = true;
9817
Douglas Gregor750734c2011-07-06 18:14:43 +00009818 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009819 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009820 // C++ [except.handle]p16:
9821 // The object declared in an exception-declaration or, if the
9822 // exception-declaration does not specify a name, a temporary (12.2) is
9823 // copy-initialized (8.5) from the exception object. [...]
9824 // The object is destroyed when the handler exits, after the destruction
9825 // of any automatic objects initialized within the handler.
9826 //
9827 // We just pretend to initialize the object with itself, then make sure
9828 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009829 QualType initType = ExDeclType;
9830
9831 InitializedEntity entity =
9832 InitializedEntity::InitializeVariable(ExDecl);
9833 InitializationKind initKind =
9834 InitializationKind::CreateCopy(Loc, SourceLocation());
9835
9836 Expr *opaqueValue =
9837 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9838 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9839 ExprResult result = sequence.Perform(*this, entity, initKind,
9840 MultiExprArg(&opaqueValue, 1));
9841 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009842 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009843 else {
9844 // If the constructor used was non-trivial, set this as the
9845 // "initializer".
9846 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9847 if (!construct->getConstructor()->isTrivial()) {
9848 Expr *init = MaybeCreateExprWithCleanups(construct);
9849 ExDecl->setInit(init);
9850 }
9851
9852 // And make sure it's destructable.
9853 FinalizeVarWithDestructor(ExDecl, recordType);
9854 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009855 }
9856 }
9857
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009858 if (Invalid)
9859 ExDecl->setInvalidDecl();
9860
9861 return ExDecl;
9862}
9863
9864/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9865/// handler.
John McCall48871652010-08-21 09:40:31 +00009866Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009867 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009868 bool Invalid = D.isInvalidType();
9869
9870 // Check for unexpanded parameter packs.
9871 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9872 UPPC_ExceptionType)) {
9873 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9874 D.getIdentifierLoc());
9875 Invalid = true;
9876 }
9877
Sebastian Redl54c04d42008-12-22 19:15:10 +00009878 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009879 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009880 LookupOrdinaryName,
9881 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009882 // The scope should be freshly made just for us. There is just no way
9883 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009884 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009885 if (PrevDecl->isTemplateParameter()) {
9886 // Maybe we will complain about the shadowed template parameter.
9887 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009888 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009889 }
9890 }
9891
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009892 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009893 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9894 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009895 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009896 }
9897
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009898 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009899 D.getSourceRange().getBegin(),
9900 D.getIdentifierLoc(),
9901 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009902 if (Invalid)
9903 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009904
Sebastian Redl54c04d42008-12-22 19:15:10 +00009905 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009906 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009907 PushOnScopeChains(ExDecl, S);
9908 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009909 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009910
Douglas Gregor758a8692009-06-17 21:51:59 +00009911 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009912 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009913}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009914
Abramo Bagnaraea947882011-03-08 16:41:52 +00009915Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009916 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009917 Expr *AssertMessageExpr_,
9918 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009919 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009920
Anders Carlsson54b26982009-03-14 00:33:21 +00009921 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009922 // In a static_assert-declaration, the constant-expression shall be a
9923 // constant expression that can be contextually converted to bool.
9924 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9925 if (Converted.isInvalid())
9926 return 0;
9927
Richard Smith902ca212011-12-14 23:32:26 +00009928 llvm::APSInt Cond;
Richard Smithf4c51d92012-02-04 09:53:13 +00009929 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9930 PDiag(diag::err_static_assert_expression_is_not_constant),
9931 /*AllowFold=*/false).isInvalid())
John McCall48871652010-08-21 09:40:31 +00009932 return 0;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009933
Richard Smith902ca212011-12-14 23:32:26 +00009934 if (!Cond)
Abramo Bagnaraea947882011-03-08 16:41:52 +00009935 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009936 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009937 }
Mike Stump11289f42009-09-09 15:08:12 +00009938
Douglas Gregoref68fee2010-12-15 23:55:21 +00009939 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9940 return 0;
9941
Abramo Bagnaraea947882011-03-08 16:41:52 +00009942 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9943 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009944
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009945 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009946 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009947}
Sebastian Redlf769df52009-03-24 22:27:57 +00009948
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009949/// \brief Perform semantic analysis of the given friend type declaration.
9950///
9951/// \returns A friend declaration that.
Abramo Bagnara254b6302011-10-29 20:52:52 +00009952FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9953 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009954 TypeSourceInfo *TSInfo) {
9955 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9956
9957 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009958 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009959
Richard Smithc8239732011-10-18 21:39:00 +00009960 // C++03 [class.friend]p2:
9961 // An elaborated-type-specifier shall be used in a friend declaration
9962 // for a class.*
9963 //
9964 // * The class-key of the elaborated-type-specifier is required.
9965 if (!ActiveTemplateInstantiations.empty()) {
9966 // Do not complain about the form of friend template types during
9967 // template instantiation; we will already have complained when the
9968 // template was declared.
9969 } else if (!T->isElaboratedTypeSpecifier()) {
9970 // If we evaluated the type to a record type, suggest putting
9971 // a tag in front.
9972 if (const RecordType *RT = T->getAs<RecordType>()) {
9973 RecordDecl *RD = RT->getDecl();
9974
9975 std::string InsertionText = std::string(" ") + RD->getKindName();
9976
9977 Diag(TypeRange.getBegin(),
9978 getLangOptions().CPlusPlus0x ?
9979 diag::warn_cxx98_compat_unelaborated_friend_type :
9980 diag::ext_unelaborated_friend_type)
9981 << (unsigned) RD->getTagKind()
9982 << T
9983 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9984 InsertionText);
9985 } else {
9986 Diag(FriendLoc,
9987 getLangOptions().CPlusPlus0x ?
9988 diag::warn_cxx98_compat_nonclass_type_friend :
9989 diag::ext_nonclass_type_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009990 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009991 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009992 }
Richard Smithc8239732011-10-18 21:39:00 +00009993 } else if (T->getAs<EnumType>()) {
9994 Diag(FriendLoc,
9995 getLangOptions().CPlusPlus0x ?
9996 diag::warn_cxx98_compat_enum_friend :
9997 diag::ext_enum_friend)
9998 << T
9999 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010000 }
10001
Douglas Gregor3b4abb62010-04-07 17:57:12 +000010002 // C++0x [class.friend]p3:
10003 // If the type specifier in a friend declaration designates a (possibly
10004 // cv-qualified) class type, that class is declared as a friend; otherwise,
10005 // the friend declaration is ignored.
10006
10007 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10008 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010009
Abramo Bagnara254b6302011-10-29 20:52:52 +000010010 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010011}
10012
John McCallace48cd2010-10-19 01:40:49 +000010013/// Handle a friend tag declaration where the scope specifier was
10014/// templated.
10015Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10016 unsigned TagSpec, SourceLocation TagLoc,
10017 CXXScopeSpec &SS,
10018 IdentifierInfo *Name, SourceLocation NameLoc,
10019 AttributeList *Attr,
10020 MultiTemplateParamsArg TempParamLists) {
10021 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10022
10023 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000010024 bool Invalid = false;
10025
10026 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +000010027 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +000010028 TempParamLists.get(),
10029 TempParamLists.size(),
10030 /*friend*/ true,
10031 isExplicitSpecialization,
10032 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000010033 if (TemplateParams->size() > 0) {
10034 // This is a declaration of a class template.
10035 if (Invalid)
10036 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010037
Eric Christopher6f228b52011-07-21 05:34:24 +000010038 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10039 SS, Name, NameLoc, Attr,
10040 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000010041 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000010042 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010043 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +000010044 } else {
10045 // The "template<>" header is extraneous.
10046 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10047 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10048 isExplicitSpecialization = true;
10049 }
10050 }
10051
10052 if (Invalid) return 0;
10053
John McCallace48cd2010-10-19 01:40:49 +000010054 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000010055 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +000010056 if (TempParamLists.get()[I]->size()) {
10057 isAllExplicitSpecializations = false;
10058 break;
10059 }
10060 }
10061
10062 // FIXME: don't ignore attributes.
10063
10064 // If it's explicit specializations all the way down, just forget
10065 // about the template header and build an appropriate non-templated
10066 // friend. TODO: for source fidelity, remember the headers.
10067 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010068 if (SS.isEmpty()) {
10069 bool Owned = false;
10070 bool IsDependent = false;
10071 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10072 Attr, AS_public,
10073 /*ModulePrivateLoc=*/SourceLocation(),
10074 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010075 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010076 /*ScopedEnumUsesClassTag=*/false,
10077 /*UnderlyingType=*/TypeResult());
10078 }
10079
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010080 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000010081 ElaboratedTypeKeyword Keyword
10082 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010083 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000010084 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000010085 if (T.isNull())
10086 return 0;
10087
10088 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10089 if (isa<DependentNameType>(T)) {
10090 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10091 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010092 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000010093 TL.setNameLoc(NameLoc);
10094 } else {
10095 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10096 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000010097 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000010098 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10099 }
10100
10101 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10102 TSI, FriendLoc);
10103 Friend->setAccess(AS_public);
10104 CurContext->addDecl(Friend);
10105 return Friend;
10106 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010107
10108 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10109
10110
John McCallace48cd2010-10-19 01:40:49 +000010111
10112 // Handle the case of a templated-scope friend class. e.g.
10113 // template <class T> class A<T>::B;
10114 // FIXME: we don't support these right now.
10115 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10116 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10117 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10118 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10119 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010120 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000010121 TL.setNameLoc(NameLoc);
10122
10123 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10124 TSI, FriendLoc);
10125 Friend->setAccess(AS_public);
10126 Friend->setUnsupportedFriend(true);
10127 CurContext->addDecl(Friend);
10128 return Friend;
10129}
10130
10131
John McCall11083da2009-09-16 22:47:08 +000010132/// Handle a friend type declaration. This works in tandem with
10133/// ActOnTag.
10134///
10135/// Notes on friend class templates:
10136///
10137/// We generally treat friend class declarations as if they were
10138/// declaring a class. So, for example, the elaborated type specifier
10139/// in a friend declaration is required to obey the restrictions of a
10140/// class-head (i.e. no typedefs in the scope chain), template
10141/// parameters are required to match up with simple template-ids, &c.
10142/// However, unlike when declaring a template specialization, it's
10143/// okay to refer to a template specialization without an empty
10144/// template parameter declaration, e.g.
10145/// friend class A<T>::B<unsigned>;
10146/// We permit this as a special case; if there are any template
10147/// parameters present at all, require proper matching, i.e.
10148/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000010149Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000010150 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010151 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +000010152
10153 assert(DS.isFriendSpecified());
10154 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10155
John McCall11083da2009-09-16 22:47:08 +000010156 // Try to convert the decl specifier to a type. This works for
10157 // friend templates because ActOnTag never produces a ClassTemplateDecl
10158 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000010159 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000010160 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10161 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000010162 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000010163 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010164
Douglas Gregor6c110f32010-12-16 01:14:37 +000010165 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10166 return 0;
10167
John McCall11083da2009-09-16 22:47:08 +000010168 // This is definitely an error in C++98. It's probably meant to
10169 // be forbidden in C++0x, too, but the specification is just
10170 // poorly written.
10171 //
10172 // The problem is with declarations like the following:
10173 // template <T> friend A<T>::foo;
10174 // where deciding whether a class C is a friend or not now hinges
10175 // on whether there exists an instantiation of A that causes
10176 // 'foo' to equal C. There are restrictions on class-heads
10177 // (which we declare (by fiat) elaborated friend declarations to
10178 // be) that makes this tractable.
10179 //
10180 // FIXME: handle "template <> friend class A<T>;", which
10181 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000010182 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000010183 Diag(Loc, diag::err_tagless_friend_type_template)
10184 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010185 return 0;
John McCall11083da2009-09-16 22:47:08 +000010186 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010187
John McCallaa74a0c2009-08-28 07:59:38 +000010188 // C++98 [class.friend]p1: A friend of a class is a function
10189 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000010190 // This is fixed in DR77, which just barely didn't make the C++03
10191 // deadline. It's also a very silly restriction that seriously
10192 // affects inner classes and which nobody else seems to implement;
10193 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000010194 //
10195 // But note that we could warn about it: it's always useless to
10196 // friend one of your own members (it's not, however, worthless to
10197 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000010198
John McCall11083da2009-09-16 22:47:08 +000010199 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010200 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000010201 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010202 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +000010203 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +000010204 TSI,
John McCall11083da2009-09-16 22:47:08 +000010205 DS.getFriendSpecLoc());
10206 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000010207 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010208
10209 if (!D)
John McCall48871652010-08-21 09:40:31 +000010210 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010211
John McCall11083da2009-09-16 22:47:08 +000010212 D->setAccess(AS_public);
10213 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000010214
John McCall48871652010-08-21 09:40:31 +000010215 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000010216}
10217
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010218Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCallde3fd222010-10-12 23:13:28 +000010219 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010220 const DeclSpec &DS = D.getDeclSpec();
10221
10222 assert(DS.isFriendSpecified());
10223 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10224
10225 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000010226 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000010227
10228 // C++ [class.friend]p1
10229 // A friend of a class is a function or class....
10230 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000010231 // It *doesn't* see through dependent types, which is correct
10232 // according to [temp.arg.type]p3:
10233 // If a declaration acquires a function type through a
10234 // type dependent on a template-parameter and this causes
10235 // a declaration that does not use the syntactic form of a
10236 // function declarator to have a function type, the program
10237 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010238 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000010239 Diag(Loc, diag::err_unexpected_friend);
10240
10241 // It might be worthwhile to try to recover by creating an
10242 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000010243 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010244 }
10245
10246 // C++ [namespace.memdef]p3
10247 // - If a friend declaration in a non-local class first declares a
10248 // class or function, the friend class or function is a member
10249 // of the innermost enclosing namespace.
10250 // - The name of the friend is not found by simple name lookup
10251 // until a matching declaration is provided in that namespace
10252 // scope (either before or after the class declaration granting
10253 // friendship).
10254 // - If a friend function is called, its name may be found by the
10255 // name lookup that considers functions from namespaces and
10256 // classes associated with the types of the function arguments.
10257 // - When looking for a prior declaration of a class or a function
10258 // declared as a friend, scopes outside the innermost enclosing
10259 // namespace scope are not considered.
10260
John McCallde3fd222010-10-12 23:13:28 +000010261 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010262 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10263 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000010264 assert(Name);
10265
Douglas Gregor6c110f32010-12-16 01:14:37 +000010266 // Check for unexpanded parameter packs.
10267 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10268 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10269 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10270 return 0;
10271
John McCall07e91c02009-08-06 02:15:43 +000010272 // The context we found the declaration in, or in which we should
10273 // create the declaration.
10274 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000010275 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010276 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000010277 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000010278
John McCallde3fd222010-10-12 23:13:28 +000010279 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +000010280
John McCallde3fd222010-10-12 23:13:28 +000010281 // There are four cases here.
10282 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +000010283 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +000010284 // there as appropriate.
10285 // Recover from invalid scope qualifiers as if they just weren't there.
10286 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +000010287 // C++0x [namespace.memdef]p3:
10288 // If the name in a friend declaration is neither qualified nor
10289 // a template-id and the declaration is a function or an
10290 // elaborated-type-specifier, the lookup to determine whether
10291 // the entity has been previously declared shall not consider
10292 // any scopes outside the innermost enclosing namespace.
10293 // C++0x [class.friend]p11:
10294 // If a friend declaration appears in a local class and the name
10295 // specified is an unqualified name, a prior declaration is
10296 // looked up without considering scopes that are outside the
10297 // innermost enclosing non-class scope. For a friend function
10298 // declaration, if there is no prior declaration, the program is
10299 // ill-formed.
10300 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +000010301 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000010302
John McCallf7cfb222010-10-13 05:45:15 +000010303 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000010304 DC = CurContext;
10305 while (true) {
10306 // Skip class contexts. If someone can cite chapter and verse
10307 // for this behavior, that would be nice --- it's what GCC and
10308 // EDG do, and it seems like a reasonable intent, but the spec
10309 // really only says that checks for unqualified existing
10310 // declarations should stop at the nearest enclosing namespace,
10311 // not that they should only consider the nearest enclosing
10312 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010313 while (DC->isRecord())
10314 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000010315
John McCall1f82f242009-11-18 22:49:29 +000010316 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +000010317
10318 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +000010319 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +000010320 break;
John McCallf7cfb222010-10-13 05:45:15 +000010321
John McCallf4776592010-10-14 22:22:28 +000010322 if (isTemplateId) {
10323 if (isa<TranslationUnitDecl>(DC)) break;
10324 } else {
10325 if (DC->isFileContext()) break;
10326 }
John McCall07e91c02009-08-06 02:15:43 +000010327 DC = DC->getParent();
10328 }
10329
10330 // C++ [class.friend]p1: A friend of a class is a function or
10331 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010332 // C++11 changes this for both friend types and functions.
John McCall93343b92009-08-06 20:49:32 +000010333 // Most C++ 98 compilers do seem to give an error here, so
10334 // we do, too.
Richard Smith0bf8a4922011-10-18 20:49:44 +000010335 if (!Previous.empty() && DC->Equals(CurContext))
10336 Diag(DS.getFriendSpecLoc(),
10337 getLangOptions().CPlusPlus0x ?
10338 diag::warn_cxx98_compat_friend_is_member :
10339 diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +000010340
John McCallccbc0322010-10-13 06:22:15 +000010341 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregordd847ba2011-11-03 16:37:14 +000010342
Douglas Gregor16e65612011-10-10 01:11:59 +000010343 // C++ [class.friend]p6:
10344 // A function can be defined in a friend declaration of a class if and
10345 // only if the class is a non-local class (9.8), the function name is
10346 // unqualified, and the function has namespace scope.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010347 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010348 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10349 }
10350
John McCallde3fd222010-10-12 23:13:28 +000010351 // - There's a non-dependent scope specifier, in which case we
10352 // compute it and do a previous lookup there for a function
10353 // or function template.
10354 } else if (!SS.getScopeRep()->isDependent()) {
10355 DC = computeDeclContext(SS);
10356 if (!DC) return 0;
10357
10358 if (RequireCompleteDeclContext(SS, DC)) return 0;
10359
10360 LookupQualifiedName(Previous, DC);
10361
10362 // Ignore things found implicitly in the wrong scope.
10363 // TODO: better diagnostics for this case. Suggesting the right
10364 // qualified scope would be nice...
10365 LookupResult::Filter F = Previous.makeFilter();
10366 while (F.hasNext()) {
10367 NamedDecl *D = F.next();
10368 if (!DC->InEnclosingNamespaceSetOf(
10369 D->getDeclContext()->getRedeclContext()))
10370 F.erase();
10371 }
10372 F.done();
10373
10374 if (Previous.empty()) {
10375 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010376 Diag(Loc, diag::err_qualified_friend_not_found)
10377 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000010378 return 0;
10379 }
10380
10381 // C++ [class.friend]p1: A friend of a class is a function or
10382 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010383 if (DC->Equals(CurContext))
10384 Diag(DS.getFriendSpecLoc(),
10385 getLangOptions().CPlusPlus0x ?
10386 diag::warn_cxx98_compat_friend_is_member :
10387 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000010388
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010389 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010390 // C++ [class.friend]p6:
10391 // A function can be defined in a friend declaration of a class if and
10392 // only if the class is a non-local class (9.8), the function name is
10393 // unqualified, and the function has namespace scope.
10394 SemaDiagnosticBuilder DB
10395 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10396
10397 DB << SS.getScopeRep();
10398 if (DC->isFileContext())
10399 DB << FixItHint::CreateRemoval(SS.getRange());
10400 SS.clear();
10401 }
John McCallde3fd222010-10-12 23:13:28 +000010402
10403 // - There's a scope specifier that does not match any template
10404 // parameter lists, in which case we use some arbitrary context,
10405 // create a method or method template, and wait for instantiation.
10406 // - There's a scope specifier that does match some template
10407 // parameter lists, which we don't handle right now.
10408 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010409 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010410 // C++ [class.friend]p6:
10411 // A function can be defined in a friend declaration of a class if and
10412 // only if the class is a non-local class (9.8), the function name is
10413 // unqualified, and the function has namespace scope.
10414 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10415 << SS.getScopeRep();
10416 }
10417
John McCallde3fd222010-10-12 23:13:28 +000010418 DC = CurContext;
10419 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000010420 }
Douglas Gregor16e65612011-10-10 01:11:59 +000010421
John McCallf7cfb222010-10-13 05:45:15 +000010422 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000010423 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000010424 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10425 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10426 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000010427 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000010428 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10429 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000010430 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010431 }
John McCall07e91c02009-08-06 02:15:43 +000010432 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010433
Douglas Gregordd847ba2011-11-03 16:37:14 +000010434 // FIXME: This is an egregious hack to cope with cases where the scope stack
10435 // does not contain the declaration context, i.e., in an out-of-line
10436 // definition of a class.
10437 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10438 if (!DCScope) {
10439 FakeDCScope.setEntity(DC);
10440 DCScope = &FakeDCScope;
10441 }
10442
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010443 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010444 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10445 move(TemplateParams), AddToScope);
John McCall48871652010-08-21 09:40:31 +000010446 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000010447
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010448 assert(ND->getDeclContext() == DC);
10449 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000010450
John McCall759e32b2009-08-31 22:39:49 +000010451 // Add the function declaration to the appropriate lookup tables,
10452 // adjusting the redeclarations list as necessary. We don't
10453 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000010454 //
John McCall759e32b2009-08-31 22:39:49 +000010455 // Also update the scope-based lookup if the target context's
10456 // lookup context is in lexical scope.
10457 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010458 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010459 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010460 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010461 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010462 }
John McCallaa74a0c2009-08-28 07:59:38 +000010463
10464 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010465 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000010466 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000010467 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000010468 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000010469
John McCallde3fd222010-10-12 23:13:28 +000010470 if (ND->isInvalidDecl())
10471 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +000010472 else {
10473 FunctionDecl *FD;
10474 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10475 FD = FTD->getTemplatedDecl();
10476 else
10477 FD = cast<FunctionDecl>(ND);
10478
10479 // Mark templated-scope function declarations as unsupported.
10480 if (FD->getNumTemplateParameterLists())
10481 FrD->setUnsupportedFriend(true);
10482 }
John McCallde3fd222010-10-12 23:13:28 +000010483
John McCall48871652010-08-21 09:40:31 +000010484 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000010485}
10486
John McCall48871652010-08-21 09:40:31 +000010487void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10488 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000010489
Sebastian Redlf769df52009-03-24 22:27:57 +000010490 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10491 if (!Fn) {
10492 Diag(DelLoc, diag::err_deleted_non_function);
10493 return;
10494 }
Douglas Gregorec9fd132012-01-14 16:38:05 +000010495 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redlf769df52009-03-24 22:27:57 +000010496 Diag(DelLoc, diag::err_deleted_decl_not_first);
10497 Diag(Prev->getLocation(), diag::note_previous_declaration);
10498 // If the declaration wasn't the first, we delete the function anyway for
10499 // recovery.
10500 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010501 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000010502}
Sebastian Redl4c018662009-04-27 21:33:24 +000010503
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010504void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10505 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10506
10507 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000010508 if (MD->getParent()->isDependentType()) {
10509 MD->setDefaulted();
10510 MD->setExplicitlyDefaulted();
10511 return;
10512 }
10513
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010514 CXXSpecialMember Member = getSpecialMember(MD);
10515 if (Member == CXXInvalid) {
10516 Diag(DefaultLoc, diag::err_default_special_members);
10517 return;
10518 }
10519
10520 MD->setDefaulted();
10521 MD->setExplicitlyDefaulted();
10522
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010523 // If this definition appears within the record, do the checking when
10524 // the record is complete.
10525 const FunctionDecl *Primary = MD;
10526 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10527 // Find the uninstantiated declaration that actually had the '= default'
10528 // on it.
10529 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10530
10531 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010532 return;
10533
10534 switch (Member) {
10535 case CXXDefaultConstructor: {
10536 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10537 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010538 if (!CD->isInvalidDecl())
10539 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10540 break;
10541 }
10542
10543 case CXXCopyConstructor: {
10544 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10545 CheckExplicitlyDefaultedCopyConstructor(CD);
10546 if (!CD->isInvalidDecl())
10547 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010548 break;
10549 }
Alexis Huntf91729462011-05-12 22:46:25 +000010550
Alexis Huntc9a55732011-05-14 05:23:28 +000010551 case CXXCopyAssignment: {
10552 CheckExplicitlyDefaultedCopyAssignment(MD);
10553 if (!MD->isInvalidDecl())
10554 DefineImplicitCopyAssignment(DefaultLoc, MD);
10555 break;
10556 }
10557
Alexis Huntf91729462011-05-12 22:46:25 +000010558 case CXXDestructor: {
10559 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10560 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010561 if (!DD->isInvalidDecl())
10562 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000010563 break;
10564 }
10565
Sebastian Redl22653ba2011-08-30 19:58:05 +000010566 case CXXMoveConstructor: {
10567 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10568 CheckExplicitlyDefaultedMoveConstructor(CD);
10569 if (!CD->isInvalidDecl())
10570 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000010571 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010572 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000010573
Sebastian Redl22653ba2011-08-30 19:58:05 +000010574 case CXXMoveAssignment: {
10575 CheckExplicitlyDefaultedMoveAssignment(MD);
10576 if (!MD->isInvalidDecl())
10577 DefineImplicitMoveAssignment(DefaultLoc, MD);
10578 break;
10579 }
10580
10581 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000010582 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010583 }
10584 } else {
10585 Diag(DefaultLoc, diag::err_default_special_members);
10586 }
10587}
10588
Sebastian Redl4c018662009-04-27 21:33:24 +000010589static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000010590 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000010591 Stmt *SubStmt = *CI;
10592 if (!SubStmt)
10593 continue;
10594 if (isa<ReturnStmt>(SubStmt))
10595 Self.Diag(SubStmt->getSourceRange().getBegin(),
10596 diag::err_return_in_constructor_handler);
10597 if (!isa<Expr>(SubStmt))
10598 SearchForReturnInStmt(Self, SubStmt);
10599 }
10600}
10601
10602void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10603 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10604 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10605 SearchForReturnInStmt(*this, Handler);
10606 }
10607}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010608
Mike Stump11289f42009-09-09 15:08:12 +000010609bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010610 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010611 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10612 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010613
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010614 if (Context.hasSameType(NewTy, OldTy) ||
10615 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010616 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010617
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010618 // Check if the return types are covariant
10619 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010620
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010621 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010622 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10623 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010624 NewClassTy = NewPT->getPointeeType();
10625 OldClassTy = OldPT->getPointeeType();
10626 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010627 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10628 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10629 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10630 NewClassTy = NewRT->getPointeeType();
10631 OldClassTy = OldRT->getPointeeType();
10632 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010633 }
10634 }
Mike Stump11289f42009-09-09 15:08:12 +000010635
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010636 // The return types aren't either both pointers or references to a class type.
10637 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010638 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010639 diag::err_different_return_type_for_overriding_virtual_function)
10640 << New->getDeclName() << NewTy << OldTy;
10641 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010642
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010643 return true;
10644 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010645
Anders Carlssone60365b2009-12-31 18:34:24 +000010646 // C++ [class.virtual]p6:
10647 // If the return type of D::f differs from the return type of B::f, the
10648 // class type in the return type of D::f shall be complete at the point of
10649 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010650 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10651 if (!RT->isBeingDefined() &&
10652 RequireCompleteType(New->getLocation(), NewClassTy,
10653 PDiag(diag::err_covariant_return_incomplete)
10654 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010655 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010656 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010657
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010658 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010659 // Check if the new class derives from the old class.
10660 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10661 Diag(New->getLocation(),
10662 diag::err_covariant_return_not_derived)
10663 << New->getDeclName() << NewTy << OldTy;
10664 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10665 return true;
10666 }
Mike Stump11289f42009-09-09 15:08:12 +000010667
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010668 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010669 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010670 diag::err_covariant_return_inaccessible_base,
10671 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10672 // FIXME: Should this point to the return type?
10673 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010674 // FIXME: this note won't trigger for delayed access control
10675 // diagnostics, and it's impossible to get an undelayed error
10676 // here from access control during the original parse because
10677 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010678 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10679 return true;
10680 }
10681 }
Mike Stump11289f42009-09-09 15:08:12 +000010682
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010683 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010684 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010685 Diag(New->getLocation(),
10686 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010687 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010688 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10689 return true;
10690 };
Mike Stump11289f42009-09-09 15:08:12 +000010691
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010692
10693 // The new class type must have the same or less qualifiers as the old type.
10694 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10695 Diag(New->getLocation(),
10696 diag::err_covariant_return_type_class_type_more_qualified)
10697 << New->getDeclName() << NewTy << OldTy;
10698 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10699 return true;
10700 };
Mike Stump11289f42009-09-09 15:08:12 +000010701
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010702 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010703}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010704
Douglas Gregor21920e372009-12-01 17:24:26 +000010705/// \brief Mark the given method pure.
10706///
10707/// \param Method the method to be marked pure.
10708///
10709/// \param InitRange the source range that covers the "0" initializer.
10710bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010711 SourceLocation EndLoc = InitRange.getEnd();
10712 if (EndLoc.isValid())
10713 Method->setRangeEnd(EndLoc);
10714
Douglas Gregor21920e372009-12-01 17:24:26 +000010715 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10716 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010717 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010718 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010719
10720 if (!Method->isInvalidDecl())
10721 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10722 << Method->getDeclName() << InitRange;
10723 return true;
10724}
10725
John McCall1f4ee7b2009-12-19 09:28:58 +000010726/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10727/// an initializer for the out-of-line declaration 'Dcl'. The scope
10728/// is a fresh scope pushed for just this purpose.
10729///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010730/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10731/// static data member of class X, names should be looked up in the scope of
10732/// class X.
John McCall48871652010-08-21 09:40:31 +000010733void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010734 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010735 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010736
John McCall1f4ee7b2009-12-19 09:28:58 +000010737 // We should only get called for declarations with scope specifiers, like:
10738 // int foo::bar;
10739 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010740 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010741}
10742
10743/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010744/// initializer for the out-of-line declaration 'D'.
10745void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010746 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010747 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010748
John McCall1f4ee7b2009-12-19 09:28:58 +000010749 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010750 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010751}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010752
10753/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10754/// C++ if/switch/while/for statement.
10755/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010756DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010757 // C++ 6.4p2:
10758 // The declarator shall not specify a function or an array.
10759 // The type-specifier-seq shall not contain typedef and shall not declare a
10760 // new class or enumeration.
10761 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10762 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010763
10764 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010765 if (!Dcl)
10766 return true;
10767
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010768 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10769 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010770 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010771 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010772 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010773
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010774 return Dcl;
10775}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010776
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010777void Sema::LoadExternalVTableUses() {
10778 if (!ExternalSource)
10779 return;
10780
10781 SmallVector<ExternalVTableUse, 4> VTables;
10782 ExternalSource->ReadUsedVTables(VTables);
10783 SmallVector<VTableUse, 4> NewUses;
10784 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10785 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10786 = VTablesUsed.find(VTables[I].Record);
10787 // Even if a definition wasn't required before, it may be required now.
10788 if (Pos != VTablesUsed.end()) {
10789 if (!Pos->second && VTables[I].DefinitionRequired)
10790 Pos->second = true;
10791 continue;
10792 }
10793
10794 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10795 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10796 }
10797
10798 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10799}
10800
Douglas Gregor88d292c2010-05-13 16:44:06 +000010801void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10802 bool DefinitionRequired) {
10803 // Ignore any vtable uses in unevaluated operands or for classes that do
10804 // not have a vtable.
10805 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10806 CurContext->isDependentContext() ||
Eli Friedman02b58512012-01-21 04:44:06 +000010807 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010808 return;
10809
Douglas Gregor88d292c2010-05-13 16:44:06 +000010810 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010811 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010812 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10813 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10814 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10815 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010816 // If we already had an entry, check to see if we are promoting this vtable
10817 // to required a definition. If so, we need to reappend to the VTableUses
10818 // list, since we may have already processed the first entry.
10819 if (DefinitionRequired && !Pos.first->second) {
10820 Pos.first->second = true;
10821 } else {
10822 // Otherwise, we can early exit.
10823 return;
10824 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010825 }
10826
10827 // Local classes need to have their virtual members marked
10828 // immediately. For all other classes, we mark their virtual members
10829 // at the end of the translation unit.
10830 if (Class->isLocalClass())
10831 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010832 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010833 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010834}
10835
Douglas Gregor88d292c2010-05-13 16:44:06 +000010836bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010837 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010838 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010839 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010840
Douglas Gregor88d292c2010-05-13 16:44:06 +000010841 // Note: The VTableUses vector could grow as a result of marking
10842 // the members of a class as "used", so we check the size each
10843 // time through the loop and prefer indices (with are stable) to
10844 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010845 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010846 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010847 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010848 if (!Class)
10849 continue;
10850
10851 SourceLocation Loc = VTableUses[I].second;
10852
10853 // If this class has a key function, but that key function is
10854 // defined in another translation unit, we don't need to emit the
10855 // vtable even though we're using it.
10856 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010857 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010858 switch (KeyFunction->getTemplateSpecializationKind()) {
10859 case TSK_Undeclared:
10860 case TSK_ExplicitSpecialization:
10861 case TSK_ExplicitInstantiationDeclaration:
10862 // The key function is in another translation unit.
10863 continue;
10864
10865 case TSK_ExplicitInstantiationDefinition:
10866 case TSK_ImplicitInstantiation:
10867 // We will be instantiating the key function.
10868 break;
10869 }
10870 } else if (!KeyFunction) {
10871 // If we have a class with no key function that is the subject
10872 // of an explicit instantiation declaration, suppress the
10873 // vtable; it will live with the explicit instantiation
10874 // definition.
10875 bool IsExplicitInstantiationDeclaration
10876 = Class->getTemplateSpecializationKind()
10877 == TSK_ExplicitInstantiationDeclaration;
10878 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10879 REnd = Class->redecls_end();
10880 R != REnd; ++R) {
10881 TemplateSpecializationKind TSK
10882 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10883 if (TSK == TSK_ExplicitInstantiationDeclaration)
10884 IsExplicitInstantiationDeclaration = true;
10885 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10886 IsExplicitInstantiationDeclaration = false;
10887 break;
10888 }
10889 }
10890
10891 if (IsExplicitInstantiationDeclaration)
10892 continue;
10893 }
10894
10895 // Mark all of the virtual members of this class as referenced, so
10896 // that we can build a vtable. Then, tell the AST consumer that a
10897 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010898 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010899 MarkVirtualMembersReferenced(Loc, Class);
10900 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10901 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10902
10903 // Optionally warn if we're emitting a weak vtable.
10904 if (Class->getLinkage() == ExternalLinkage &&
10905 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010906 const FunctionDecl *KeyFunctionDef = 0;
10907 if (!KeyFunction ||
10908 (KeyFunction->hasBody(KeyFunctionDef) &&
10909 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000010910 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10911 TSK_ExplicitInstantiationDefinition
10912 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10913 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010914 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010915 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010916 VTableUses.clear();
10917
Douglas Gregor97509692011-04-22 22:25:37 +000010918 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010919}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010920
Rafael Espindola5b334082010-03-26 00:36:59 +000010921void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10922 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010923 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10924 e = RD->method_end(); i != e; ++i) {
10925 CXXMethodDecl *MD = *i;
10926
10927 // C++ [basic.def.odr]p2:
10928 // [...] A virtual member function is used if it is not pure. [...]
10929 if (MD->isVirtual() && !MD->isPure())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010930 MarkFunctionReferenced(Loc, MD);
Anders Carlsson82fccd02009-12-07 08:24:59 +000010931 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010932
10933 // Only classes that have virtual bases need a VTT.
10934 if (RD->getNumVBases() == 0)
10935 return;
10936
10937 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10938 e = RD->bases_end(); i != e; ++i) {
10939 const CXXRecordDecl *Base =
10940 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010941 if (Base->getNumVBases() == 0)
10942 continue;
10943 MarkVirtualMembersReferenced(Loc, Base);
10944 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010945}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010946
10947/// SetIvarInitializers - This routine builds initialization ASTs for the
10948/// Objective-C implementation whose ivars need be initialized.
10949void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10950 if (!getLangOptions().CPlusPlus)
10951 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010952 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010953 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010954 CollectIvarsToConstructOrDestruct(OID, ivars);
10955 if (ivars.empty())
10956 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010957 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010958 for (unsigned i = 0; i < ivars.size(); i++) {
10959 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010960 if (Field->isInvalidDecl())
10961 continue;
10962
Alexis Hunt1d792652011-01-08 20:30:50 +000010963 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010964 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10965 InitializationKind InitKind =
10966 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10967
10968 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010969 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010970 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010971 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010972 // Note, MemberInit could actually come back empty if no initialization
10973 // is required (e.g., because it would call a trivial default constructor)
10974 if (!MemberInit.get() || MemberInit.isInvalid())
10975 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010976
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010977 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010978 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10979 SourceLocation(),
10980 MemberInit.takeAs<Expr>(),
10981 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010982 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010983
10984 // Be sure that the destructor is accessible and is marked as referenced.
10985 if (const RecordType *RecordTy
10986 = Context.getBaseElementType(Field->getType())
10987 ->getAs<RecordType>()) {
10988 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010989 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010990 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000010991 CheckDestructorAccess(Field->getLocation(), Destructor,
10992 PDiag(diag::err_access_dtor_ivar)
10993 << Context.getBaseElementType(Field->getType()));
10994 }
10995 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010996 }
10997 ObjCImplementation->setIvarInitializers(Context,
10998 AllToInit.data(), AllToInit.size());
10999 }
11000}
Alexis Hunt6118d662011-05-04 05:57:24 +000011001
Alexis Hunt27a761d2011-05-04 23:29:54 +000011002static
11003void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11004 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11005 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11006 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11007 Sema &S) {
11008 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11009 CE = Current.end();
11010 if (Ctor->isInvalidDecl())
11011 return;
11012
11013 const FunctionDecl *FNTarget = 0;
11014 CXXConstructorDecl *Target;
11015
11016 // We ignore the result here since if we don't have a body, Target will be
11017 // null below.
11018 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11019 Target
11020= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11021
11022 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11023 // Avoid dereferencing a null pointer here.
11024 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11025
11026 if (!Current.insert(Canonical))
11027 return;
11028
11029 // We know that beyond here, we aren't chaining into a cycle.
11030 if (!Target || !Target->isDelegatingConstructor() ||
11031 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11032 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11033 Valid.insert(*CI);
11034 Current.clear();
11035 // We've hit a cycle.
11036 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11037 Current.count(TCanonical)) {
11038 // If we haven't diagnosed this cycle yet, do so now.
11039 if (!Invalid.count(TCanonical)) {
11040 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000011041 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000011042 << Ctor;
11043
11044 // Don't add a note for a function delegating directo to itself.
11045 if (TCanonical != Canonical)
11046 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11047
11048 CXXConstructorDecl *C = Target;
11049 while (C->getCanonicalDecl() != Canonical) {
11050 (void)C->getTargetConstructor()->hasBody(FNTarget);
11051 assert(FNTarget && "Ctor cycle through bodiless function");
11052
11053 C
11054 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11055 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11056 }
11057 }
11058
11059 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11060 Invalid.insert(*CI);
11061 Current.clear();
11062 } else {
11063 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11064 }
11065}
11066
11067
Alexis Hunt6118d662011-05-04 05:57:24 +000011068void Sema::CheckDelegatingCtorCycles() {
11069 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11070
Alexis Hunt27a761d2011-05-04 23:29:54 +000011071 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11072 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000011073
Douglas Gregorbae31202011-07-27 21:57:17 +000011074 for (DelegatingCtorDeclsType::iterator
11075 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000011076 E = DelegatingCtorDecls.end();
11077 I != E; ++I) {
11078 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000011079 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000011080
11081 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11082 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000011083}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011084
11085/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11086Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11087 // Implicitly declared functions (e.g. copy constructors) are
11088 // __host__ __device__
11089 if (D->isImplicit())
11090 return CFT_HostDevice;
11091
11092 if (D->hasAttr<CUDAGlobalAttr>())
11093 return CFT_Global;
11094
11095 if (D->hasAttr<CUDADeviceAttr>()) {
11096 if (D->hasAttr<CUDAHostAttr>())
11097 return CFT_HostDevice;
11098 else
11099 return CFT_Device;
11100 }
11101
11102 return CFT_Host;
11103}
11104
11105bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11106 CUDAFunctionTarget CalleeTarget) {
11107 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11108 // Callable from the device only."
11109 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11110 return true;
11111
11112 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11113 // Callable from the host only."
11114 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11115 // Callable from the host only."
11116 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11117 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11118 return true;
11119
11120 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11121 return true;
11122
11123 return false;
11124}