blob: 8ba84fe86a50d8b82e45c2e29850cc41f899c966 [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;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000818
819 if (Field->isAnonymousStructOrUnion() &&
820 Field->getType()->getAsCXXRecordDecl()->isEmpty())
821 return;
822
Richard Smitheb3c10c2011-10-01 02:31:28 +0000823 if (!Inits.count(Field)) {
824 if (!Diagnosed) {
825 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
826 Diagnosed = true;
827 }
828 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
829 } else if (Field->isAnonymousStructOrUnion()) {
830 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
831 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
832 I != E; ++I)
833 // If an anonymous union contains an anonymous struct of which any member
834 // is initialized, all members must be initialized.
835 if (!RD->isUnion() || Inits.count(*I))
836 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
837 }
838}
839
840/// Check the body for the given constexpr function declaration only contains
841/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
842///
843/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith2de5a932012-02-05 02:30:54 +0000844bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body,
845 bool IsInstantiation) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000846 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +0000847 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000848 // The definition of a constexpr function shall satisfy the following
849 // constraints: [...]
850 // - its function-body shall be = delete, = default, or a
851 // compound-statement
852 //
Richard Smith74388b42012-02-04 00:33:54 +0000853 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000854 // In the definition of a constexpr constructor, [...]
855 // - its function-body shall not be a function-try-block;
856 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860
861 // - its function-body shall be [...] a compound-statement that contains only
862 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
863
864 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
865 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
866 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
867 switch ((*BodyIt)->getStmtClass()) {
868 case Stmt::NullStmtClass:
869 // - null statements,
870 continue;
871
872 case Stmt::DeclStmtClass:
873 // - static_assert-declarations
874 // - using-declarations,
875 // - using-directives,
876 // - typedef declarations and alias-declarations that do not define
877 // classes or enumerations,
878 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
879 return false;
880 continue;
881
882 case Stmt::ReturnStmtClass:
883 // - and exactly one return statement;
884 if (isa<CXXConstructorDecl>(Dcl))
885 break;
886
887 ReturnStmts.push_back((*BodyIt)->getLocStart());
888 // FIXME
889 // - every constructor call and implicit conversion used in initializing
890 // the return value shall be one of those allowed in a constant
891 // expression.
892 // Deal with this as part of a general check that the function can produce
893 // a constant expression (for [dcl.constexpr]p5).
894 continue;
895
896 default:
897 break;
898 }
899
900 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904
905 if (const CXXConstructorDecl *Constructor
906 = dyn_cast<CXXConstructorDecl>(Dcl)) {
907 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +0000908 // DR1359:
909 // - every non-variant non-static data member and base class sub-object
910 // shall be initialized;
911 // - if the class is a non-empty union, or for each non-empty anonymous
912 // union member of a non-union class, exactly one non-static data member
913 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000914 if (RD->isUnion()) {
Richard Smith4d59eeb2012-02-09 06:40:58 +0000915 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000916 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
917 return false;
918 }
Richard Smithf368fb42011-10-10 16:38:04 +0000919 } else if (!Constructor->isDependentContext() &&
920 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000921 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
922
923 // Skip detailed checking if we have enough initializers, and we would
924 // allow at most one initializer per member.
925 bool AnyAnonStructUnionMembers = false;
926 unsigned Fields = 0;
927 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
928 E = RD->field_end(); I != E; ++I, ++Fields) {
929 if ((*I)->isAnonymousStructOrUnion()) {
930 AnyAnonStructUnionMembers = true;
931 break;
932 }
933 }
934 if (AnyAnonStructUnionMembers ||
935 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
936 // Check initialization of non-static data members. Base classes are
937 // always initialized so do not need to be checked. Dependent bases
938 // might not have initializers in the member initializer list.
939 llvm::SmallSet<Decl*, 16> Inits;
940 for (CXXConstructorDecl::init_const_iterator
941 I = Constructor->init_begin(), E = Constructor->init_end();
942 I != E; ++I) {
943 if (FieldDecl *FD = (*I)->getMember())
944 Inits.insert(FD);
945 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
946 Inits.insert(ID->chain_begin(), ID->chain_end());
947 }
948
949 bool Diagnosed = false;
950 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
951 E = RD->field_end(); I != E; ++I)
952 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
953 if (Diagnosed)
954 return false;
955 }
956 }
957
958 // FIXME
959 // - every constructor involved in initializing non-static data members
960 // and base class sub-objects shall be a constexpr constructor;
961 // - every assignment-expression that is an initializer-clause appearing
962 // directly or indirectly within a brace-or-equal-initializer for
963 // a non-static data member that is not named by a mem-initializer-id
964 // shall be a constant expression; and
965 // - every implicit conversion used in converting a constructor argument
966 // to the corresponding parameter type and converting
967 // a full-expression to the corresponding member type shall be one of
968 // those allowed in a constant expression.
969 // Deal with these as part of a general check that the function can produce
970 // a constant expression (for [dcl.constexpr]p5).
971 } else {
972 if (ReturnStmts.empty()) {
973 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
974 return false;
975 }
976 if (ReturnStmts.size() > 1) {
977 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
978 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
979 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
980 return false;
981 }
982 }
983
Richard Smith74388b42012-02-04 00:33:54 +0000984 // C++11 [dcl.constexpr]p5:
985 // if no function argument values exist such that the function invocation
986 // substitution would produce a constant expression, the program is
987 // ill-formed; no diagnostic required.
988 // C++11 [dcl.constexpr]p3:
989 // - every constructor call and implicit conversion used in initializing the
990 // return value shall be one of those allowed in a constant expression.
991 // C++11 [dcl.constexpr]p4:
992 // - every constructor involved in initializing non-static data members and
993 // base class sub-objects shall be a constexpr constructor.
Richard Smith253c2a32012-01-27 01:14:48 +0000994 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smithda7c4ba2012-02-08 06:14:53 +0000995 if (!IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith253c2a32012-01-27 01:14:48 +0000996 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
997 << isa<CXXConstructorDecl>(Dcl);
998 for (size_t I = 0, N = Diags.size(); I != N; ++I)
999 Diag(Diags[I].first, Diags[I].second);
1000 return false;
1001 }
1002
Richard Smitheb3c10c2011-10-01 02:31:28 +00001003 return true;
1004}
1005
Douglas Gregor61956c42008-10-31 09:07:45 +00001006/// isCurrentClassName - Determine whether the identifier II is the
1007/// name of the class type currently being defined. In the case of
1008/// nested classes, this will only return true if II is the name of
1009/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001010bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1011 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001012 assert(getLangOptions().CPlusPlus && "No class names in C!");
1013
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001014 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001015 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001016 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001017 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1018 } else
1019 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1020
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001021 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001022 return &II == CurDecl->getIdentifier();
1023 else
1024 return false;
1025}
1026
Mike Stump11289f42009-09-09 15:08:12 +00001027/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001028///
1029/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1030/// and returns NULL otherwise.
1031CXXBaseSpecifier *
1032Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1033 SourceRange SpecifierRange,
1034 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001035 TypeSourceInfo *TInfo,
1036 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001037 QualType BaseType = TInfo->getType();
1038
Douglas Gregor463421d2009-03-03 04:44:36 +00001039 // C++ [class.union]p1:
1040 // A union shall not have base classes.
1041 if (Class->isUnion()) {
1042 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1043 << SpecifierRange;
1044 return 0;
1045 }
1046
Douglas Gregor752a5952011-01-03 22:36:02 +00001047 if (EllipsisLoc.isValid() &&
1048 !TInfo->getType()->containsUnexpandedParameterPack()) {
1049 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1050 << TInfo->getTypeLoc().getSourceRange();
1051 EllipsisLoc = SourceLocation();
1052 }
1053
Douglas Gregor463421d2009-03-03 04:44:36 +00001054 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +00001055 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001056 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001057 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001058
1059 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +00001060
1061 // Base specifiers must be record types.
1062 if (!BaseType->isRecordType()) {
1063 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1064 return 0;
1065 }
1066
1067 // C++ [class.union]p1:
1068 // A union shall not be used as a base class.
1069 if (BaseType->isUnionType()) {
1070 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1071 return 0;
1072 }
1073
1074 // C++ [class.derived]p2:
1075 // The class-name in a base-specifier shall not be an incompletely
1076 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001077 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00001078 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +00001079 << SpecifierRange)) {
1080 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001081 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001082 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001083
Eli Friedmanc96d4962009-08-15 21:55:26 +00001084 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001085 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001086 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001087 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001088 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +00001089 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1090 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001091
Anders Carlsson65c76d32011-03-25 14:55:14 +00001092 // C++ [class]p3:
1093 // If a class is marked final and it appears as a base-type-specifier in
1094 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001095 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001096 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1097 << CXXBaseDecl->getDeclName();
1098 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1099 << CXXBaseDecl->getDeclName();
1100 return 0;
1101 }
1102
John McCall3696dcb2010-08-17 07:23:57 +00001103 if (BaseDecl->isInvalidDecl())
1104 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001105
1106 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001107 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001108 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001109 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001110}
1111
Douglas Gregor556877c2008-04-13 21:30:24 +00001112/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1113/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001114/// example:
1115/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001116/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001117BaseResult
John McCall48871652010-08-21 09:40:31 +00001118Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +00001119 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001120 ParsedType basetype, SourceLocation BaseLoc,
1121 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001122 if (!classdecl)
1123 return true;
1124
Douglas Gregorc40290e2009-03-09 23:48:35 +00001125 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001126 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001127 if (!Class)
1128 return true;
1129
Nick Lewycky19b9f952010-07-26 16:56:01 +00001130 TypeSourceInfo *TInfo = 0;
1131 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001132
Douglas Gregor752a5952011-01-03 22:36:02 +00001133 if (EllipsisLoc.isInvalid() &&
1134 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001135 UPPC_BaseType))
1136 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001137
Douglas Gregor463421d2009-03-03 04:44:36 +00001138 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001139 Virtual, Access, TInfo,
1140 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001141 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +00001142
Douglas Gregor463421d2009-03-03 04:44:36 +00001143 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001144}
Douglas Gregor556877c2008-04-13 21:30:24 +00001145
Douglas Gregor463421d2009-03-03 04:44:36 +00001146/// \brief Performs the actual work of attaching the given base class
1147/// specifiers to a C++ class.
1148bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1149 unsigned NumBases) {
1150 if (NumBases == 0)
1151 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001152
1153 // Used to keep track of which base types we have already seen, so
1154 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001155 // that the key is always the unqualified canonical type of the base
1156 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001157 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1158
1159 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001160 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001161 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001162 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001163 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001164 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001165 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +00001166 if (KnownBaseTypes[NewBaseType]) {
1167 // C++ [class.mi]p3:
1168 // A class shall not be specified as a direct base class of a
1169 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +00001170 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001171 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001172 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001173 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001174
1175 // Delete the duplicate base class specifier; we're going to
1176 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001177 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001178
1179 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001180 } else {
1181 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +00001182 KnownBaseTypes[NewBaseType] = Bases[idx];
1183 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian28f5fb92011-10-24 17:30:45 +00001184 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian47f9a732011-10-21 22:27:12 +00001185 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1186 if (RD->hasAttr<WeakAttr>())
1187 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregor29a92472008-10-22 17:49:05 +00001188 }
1189 }
1190
1191 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001192 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001193
1194 // Delete the remaining (good) base class specifiers, since their
1195 // data has been copied into the CXXRecordDecl.
1196 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001197 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001198
1199 return Invalid;
1200}
1201
1202/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1203/// class, after checking whether there are any duplicate base
1204/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001205void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001206 unsigned NumBases) {
1207 if (!ClassDecl || !Bases || !NumBases)
1208 return;
1209
1210 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001211 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001212 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001213}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001214
John McCalle78aac42010-03-10 03:28:59 +00001215static CXXRecordDecl *GetClassForType(QualType T) {
1216 if (const RecordType *RT = T->getAs<RecordType>())
1217 return cast<CXXRecordDecl>(RT->getDecl());
1218 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1219 return ICT->getDecl();
1220 else
1221 return 0;
1222}
1223
Douglas Gregor36d1b142009-10-06 17:59:45 +00001224/// \brief Determine whether the type \p Derived is a C++ class that is
1225/// derived from the type \p Base.
1226bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1227 if (!getLangOptions().CPlusPlus)
1228 return false;
John McCalle78aac42010-03-10 03:28:59 +00001229
1230 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1231 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001232 return false;
1233
John McCalle78aac42010-03-10 03:28:59 +00001234 CXXRecordDecl *BaseRD = GetClassForType(Base);
1235 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001236 return false;
1237
John McCall67da35c2010-02-04 22:26:26 +00001238 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1239 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001240}
1241
1242/// \brief Determine whether the type \p Derived is a C++ class that is
1243/// derived from the type \p Base.
1244bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1245 if (!getLangOptions().CPlusPlus)
1246 return false;
1247
John McCalle78aac42010-03-10 03:28:59 +00001248 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1249 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001250 return false;
1251
John McCalle78aac42010-03-10 03:28:59 +00001252 CXXRecordDecl *BaseRD = GetClassForType(Base);
1253 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001254 return false;
1255
Douglas Gregor36d1b142009-10-06 17:59:45 +00001256 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1257}
1258
Anders Carlssona70cff62010-04-24 19:06:50 +00001259void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001260 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001261 assert(BasePathArray.empty() && "Base path array must be empty!");
1262 assert(Paths.isRecordingPaths() && "Must record paths!");
1263
1264 const CXXBasePath &Path = Paths.front();
1265
1266 // We first go backward and check if we have a virtual base.
1267 // FIXME: It would be better if CXXBasePath had the base specifier for
1268 // the nearest virtual base.
1269 unsigned Start = 0;
1270 for (unsigned I = Path.size(); I != 0; --I) {
1271 if (Path[I - 1].Base->isVirtual()) {
1272 Start = I - 1;
1273 break;
1274 }
1275 }
1276
1277 // Now add all bases.
1278 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001279 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001280}
1281
Douglas Gregor88d292c2010-05-13 16:44:06 +00001282/// \brief Determine whether the given base path includes a virtual
1283/// base class.
John McCallcf142162010-08-07 06:22:56 +00001284bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1285 for (CXXCastPath::const_iterator B = BasePath.begin(),
1286 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001287 B != BEnd; ++B)
1288 if ((*B)->isVirtual())
1289 return true;
1290
1291 return false;
1292}
1293
Douglas Gregor36d1b142009-10-06 17:59:45 +00001294/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1295/// conversion (where Derived and Base are class types) is
1296/// well-formed, meaning that the conversion is unambiguous (and
1297/// that all of the base classes are accessible). Returns true
1298/// and emits a diagnostic if the code is ill-formed, returns false
1299/// otherwise. Loc is the location where this routine should point to
1300/// if there is an error, and Range is the source range to highlight
1301/// if there is an error.
1302bool
1303Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001304 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001305 unsigned AmbigiousBaseConvID,
1306 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001307 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001308 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001309 // First, determine whether the path from Derived to Base is
1310 // ambiguous. This is slightly more expensive than checking whether
1311 // the Derived to Base conversion exists, because here we need to
1312 // explore multiple paths to determine if there is an ambiguity.
1313 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1314 /*DetectVirtual=*/false);
1315 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1316 assert(DerivationOkay &&
1317 "Can only be used with a derived-to-base conversion");
1318 (void)DerivationOkay;
1319
1320 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001321 if (InaccessibleBaseID) {
1322 // Check that the base class can be accessed.
1323 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1324 InaccessibleBaseID)) {
1325 case AR_inaccessible:
1326 return true;
1327 case AR_accessible:
1328 case AR_dependent:
1329 case AR_delayed:
1330 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001331 }
John McCall5b0829a2010-02-10 09:31:12 +00001332 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001333
1334 // Build a base path if necessary.
1335 if (BasePath)
1336 BuildBasePathArray(Paths, *BasePath);
1337 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001338 }
1339
1340 // We know that the derived-to-base conversion is ambiguous, and
1341 // we're going to produce a diagnostic. Perform the derived-to-base
1342 // search just one more time to compute all of the possible paths so
1343 // that we can print them out. This is more expensive than any of
1344 // the previous derived-to-base checks we've done, but at this point
1345 // performance isn't as much of an issue.
1346 Paths.clear();
1347 Paths.setRecordingPaths(true);
1348 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1349 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1350 (void)StillOkay;
1351
1352 // Build up a textual representation of the ambiguous paths, e.g.,
1353 // D -> B -> A, that will be used to illustrate the ambiguous
1354 // conversions in the diagnostic. We only print one of the paths
1355 // to each base class subobject.
1356 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1357
1358 Diag(Loc, AmbigiousBaseConvID)
1359 << Derived << Base << PathDisplayStr << Range << Name;
1360 return true;
1361}
1362
1363bool
1364Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001365 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001366 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001367 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001368 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001369 IgnoreAccess ? 0
1370 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001371 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001372 Loc, Range, DeclarationName(),
1373 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001374}
1375
1376
1377/// @brief Builds a string representing ambiguous paths from a
1378/// specific derived class to different subobjects of the same base
1379/// class.
1380///
1381/// This function builds a string that can be used in error messages
1382/// to show the different paths that one can take through the
1383/// inheritance hierarchy to go from the derived class to different
1384/// subobjects of a base class. The result looks something like this:
1385/// @code
1386/// struct D -> struct B -> struct A
1387/// struct D -> struct C -> struct A
1388/// @endcode
1389std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1390 std::string PathDisplayStr;
1391 std::set<unsigned> DisplayedPaths;
1392 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1393 Path != Paths.end(); ++Path) {
1394 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1395 // We haven't displayed a path to this particular base
1396 // class subobject yet.
1397 PathDisplayStr += "\n ";
1398 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1399 for (CXXBasePath::const_iterator Element = Path->begin();
1400 Element != Path->end(); ++Element)
1401 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1402 }
1403 }
1404
1405 return PathDisplayStr;
1406}
1407
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001408//===----------------------------------------------------------------------===//
1409// C++ class member Handling
1410//===----------------------------------------------------------------------===//
1411
Abramo Bagnarad7340582010-06-05 05:09:32 +00001412/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001413bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1414 SourceLocation ASLoc,
1415 SourceLocation ColonLoc,
1416 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001417 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001418 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001419 ASLoc, ColonLoc);
1420 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001421 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001422}
1423
Anders Carlssonfd835532011-01-20 05:57:14 +00001424/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001425void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001426 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001427 if (!MD || !MD->isVirtual())
1428 return;
1429
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001430 if (MD->isDependentContext())
1431 return;
1432
Anders Carlssonfd835532011-01-20 05:57:14 +00001433 // C++0x [class.virtual]p3:
1434 // If a virtual function is marked with the virt-specifier override and does
1435 // not override a member function of a base class,
1436 // the program is ill-formed.
1437 bool HasOverriddenMethods =
1438 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001439 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001440 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001441 diag::err_function_marked_override_not_overriding)
1442 << MD->getDeclName();
1443 return;
1444 }
1445}
1446
Anders Carlsson3f610c72011-01-20 16:25:36 +00001447/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1448/// function overrides a virtual member function marked 'final', according to
1449/// C++0x [class.virtual]p3.
1450bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1451 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001452 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001453 return false;
1454
1455 Diag(New->getLocation(), diag::err_final_function_overridden)
1456 << New->getDeclName();
1457 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1458 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001459}
1460
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001461/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1462/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001463/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1464/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1465/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001466Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001467Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001468 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001469 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001470 bool HasDeferredInit) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001471 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001472 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1473 DeclarationName Name = NameInfo.getName();
1474 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001475
1476 // For anonymous bitfields, the location should point to the type.
1477 if (Loc.isInvalid())
1478 Loc = D.getSourceRange().getBegin();
1479
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001480 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001481
John McCallb1cd7da2010-06-04 08:34:12 +00001482 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001483 assert(!DS.isFriendSpecified());
1484
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001485 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001486
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001487 // C++ 9.2p6: A member shall not be declared to have automatic storage
1488 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001489 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1490 // data members and cannot be applied to names declared const or static,
1491 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001492 switch (DS.getStorageClassSpec()) {
1493 case DeclSpec::SCS_unspecified:
1494 case DeclSpec::SCS_typedef:
1495 case DeclSpec::SCS_static:
1496 // FALL THROUGH.
1497 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001498 case DeclSpec::SCS_mutable:
1499 if (isFunc) {
1500 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001501 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001502 else
Chris Lattner3b054132008-11-19 05:08:23 +00001503 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001504
Sebastian Redl8071edb2008-11-17 23:24:37 +00001505 // FIXME: It would be nicer if the keyword was ignored only for this
1506 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001507 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001508 }
1509 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001510 default:
1511 if (DS.getStorageClassSpecLoc().isValid())
1512 Diag(DS.getStorageClassSpecLoc(),
1513 diag::err_storageclass_invalid_for_member);
1514 else
1515 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1516 D.getMutableDeclSpec().ClearStorageClassSpecs();
1517 }
1518
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001519 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1520 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001521 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001522
1523 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001524 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001525 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001526
1527 // Data members must have identifiers for names.
1528 if (Name.getNameKind() != DeclarationName::Identifier) {
1529 Diag(Loc, diag::err_bad_variable_name)
1530 << Name;
1531 return 0;
1532 }
Douglas Gregora007d362010-10-13 22:19:53 +00001533
Douglas Gregor7c26c042011-09-21 14:40:46 +00001534 IdentifierInfo *II = Name.getAsIdentifierInfo();
1535
1536 // Member field could not be with "template" keyword.
1537 // So TemplateParameterLists should be empty in this case.
1538 if (TemplateParameterLists.size()) {
1539 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1540 if (TemplateParams->size()) {
1541 // There is no such thing as a member field template.
1542 Diag(D.getIdentifierLoc(), diag::err_template_member)
1543 << II
1544 << SourceRange(TemplateParams->getTemplateLoc(),
1545 TemplateParams->getRAngleLoc());
1546 } else {
1547 // There is an extraneous 'template<>' for this member.
1548 Diag(TemplateParams->getTemplateLoc(),
1549 diag::err_template_member_noparams)
1550 << II
1551 << SourceRange(TemplateParams->getTemplateLoc(),
1552 TemplateParams->getRAngleLoc());
1553 }
1554 return 0;
1555 }
1556
Douglas Gregora007d362010-10-13 22:19:53 +00001557 if (SS.isSet() && !SS.isInvalid()) {
1558 // The user provided a superfluous scope specifier inside a class
1559 // definition:
1560 //
1561 // class X {
1562 // int X::member;
1563 // };
1564 DeclContext *DC = 0;
1565 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1566 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001567 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregora007d362010-10-13 22:19:53 +00001568 else
1569 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1570 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001571
Douglas Gregora007d362010-10-13 22:19:53 +00001572 SS.clear();
1573 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001574
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001575 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001576 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001577 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001578 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001579 assert(!HasDeferredInit);
1580
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001581 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner97e277e2009-03-05 23:03:49 +00001582 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001583 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001584 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001585
1586 // Non-instance-fields can't have a bitfield.
1587 if (BitWidth) {
1588 if (Member->isInvalidDecl()) {
1589 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001590 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001591 // C++ 9.6p3: A bit-field shall not be a static member.
1592 // "static member 'A' cannot be a bit-field"
1593 Diag(Loc, diag::err_static_not_bitfield)
1594 << Name << BitWidth->getSourceRange();
1595 } else if (isa<TypedefDecl>(Member)) {
1596 // "typedef member 'x' cannot be a bit-field"
1597 Diag(Loc, diag::err_typedef_not_bitfield)
1598 << Name << BitWidth->getSourceRange();
1599 } else {
1600 // A function typedef ("typedef int f(); f a;").
1601 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1602 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001603 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001604 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001605 }
Mike Stump11289f42009-09-09 15:08:12 +00001606
Chris Lattnerd26760a2009-03-05 23:01:03 +00001607 BitWidth = 0;
1608 Member->setInvalidDecl();
1609 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001610
1611 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregor3447e762009-08-20 22:52:58 +00001613 // If we have declared a member function template, set the access of the
1614 // templated declaration as well.
1615 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1616 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001617 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001618
Anders Carlsson13a69102011-01-20 04:34:22 +00001619 if (VS.isOverrideSpecified()) {
1620 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1621 if (!MD || !MD->isVirtual()) {
1622 Diag(Member->getLocStart(),
1623 diag::override_keyword_only_allowed_on_virtual_member_functions)
1624 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001625 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001626 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001627 }
1628 if (VS.isFinalSpecified()) {
1629 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1630 if (!MD || !MD->isVirtual()) {
1631 Diag(Member->getLocStart(),
1632 diag::override_keyword_only_allowed_on_virtual_member_functions)
1633 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001634 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001635 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001636 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001637
Douglas Gregorf2f08062011-03-08 17:10:18 +00001638 if (VS.getLastLocation().isValid()) {
1639 // Update the end location of a method that has a virt-specifiers.
1640 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1641 MD->setRangeEnd(VS.getLastLocation());
1642 }
1643
Anders Carlssonc87f8612011-01-20 06:29:02 +00001644 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001645
Douglas Gregor92751d42008-11-17 22:58:34 +00001646 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001647
John McCall25849ca2011-02-15 07:12:36 +00001648 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001649 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001650 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001651}
1652
Richard Smith938f40b2011-06-11 17:19:42 +00001653/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001654/// in-class initializer for a non-static C++ class member, and after
1655/// instantiating an in-class initializer in a class template. Such actions
1656/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001657void
1658Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1659 Expr *InitExpr) {
1660 FieldDecl *FD = cast<FieldDecl>(D);
1661
1662 if (!InitExpr) {
1663 FD->setInvalidDecl();
1664 FD->removeInClassInitializer();
1665 return;
1666 }
1667
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00001668 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1669 FD->setInvalidDecl();
1670 FD->removeInClassInitializer();
1671 return;
1672 }
1673
Richard Smith938f40b2011-06-11 17:19:42 +00001674 ExprResult Init = InitExpr;
1675 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1676 // FIXME: if there is no EqualLoc, this is list-initialization.
1677 Init = PerformCopyInitialization(
1678 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1679 if (Init.isInvalid()) {
1680 FD->setInvalidDecl();
1681 return;
1682 }
1683
1684 CheckImplicitConversions(Init.get(), EqualLoc);
1685 }
1686
1687 // C++0x [class.base.init]p7:
1688 // The initialization of each base and member constitutes a
1689 // full-expression.
1690 Init = MaybeCreateExprWithCleanups(Init);
1691 if (Init.isInvalid()) {
1692 FD->setInvalidDecl();
1693 return;
1694 }
1695
1696 InitExpr = Init.release();
1697
1698 FD->setInClassInitializer(InitExpr);
1699}
1700
Douglas Gregor15e77a22009-12-31 09:10:24 +00001701/// \brief Find the direct and/or virtual base specifiers that
1702/// correspond to the given base type, for use in base initialization
1703/// within a constructor.
1704static bool FindBaseInitializer(Sema &SemaRef,
1705 CXXRecordDecl *ClassDecl,
1706 QualType BaseType,
1707 const CXXBaseSpecifier *&DirectBaseSpec,
1708 const CXXBaseSpecifier *&VirtualBaseSpec) {
1709 // First, check for a direct base class.
1710 DirectBaseSpec = 0;
1711 for (CXXRecordDecl::base_class_const_iterator Base
1712 = ClassDecl->bases_begin();
1713 Base != ClassDecl->bases_end(); ++Base) {
1714 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1715 // We found a direct base of this type. That's what we're
1716 // initializing.
1717 DirectBaseSpec = &*Base;
1718 break;
1719 }
1720 }
1721
1722 // Check for a virtual base class.
1723 // FIXME: We might be able to short-circuit this if we know in advance that
1724 // there are no virtual bases.
1725 VirtualBaseSpec = 0;
1726 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1727 // We haven't found a base yet; search the class hierarchy for a
1728 // virtual base class.
1729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1730 /*DetectVirtual=*/false);
1731 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1732 BaseType, Paths)) {
1733 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1734 Path != Paths.end(); ++Path) {
1735 if (Path->back().Base->isVirtual()) {
1736 VirtualBaseSpec = Path->back().Base;
1737 break;
1738 }
1739 }
1740 }
1741 }
1742
1743 return DirectBaseSpec || VirtualBaseSpec;
1744}
1745
Sebastian Redla74948d2011-09-24 17:48:25 +00001746/// \brief Handle a C++ member initializer using braced-init-list syntax.
1747MemInitResult
1748Sema::ActOnMemInitializer(Decl *ConstructorD,
1749 Scope *S,
1750 CXXScopeSpec &SS,
1751 IdentifierInfo *MemberOrBase,
1752 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001753 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001754 SourceLocation IdLoc,
1755 Expr *InitList,
1756 SourceLocation EllipsisLoc) {
1757 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001758 DS, IdLoc, MultiInitializer(InitList),
1759 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00001760}
1761
1762/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001763MemInitResult
John McCall48871652010-08-21 09:40:31 +00001764Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001765 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001766 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001767 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001768 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001769 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001770 SourceLocation IdLoc,
1771 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001772 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001773 SourceLocation RParenLoc,
1774 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001775 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001776 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1777 NumArgs, RParenLoc),
Sebastian Redla74948d2011-09-24 17:48:25 +00001778 EllipsisLoc);
1779}
1780
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001781namespace {
1782
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00001783// Callback to only accept typo corrections that can be a valid C++ member
1784// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001785class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1786 public:
1787 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1788 : ClassDecl(ClassDecl) {}
1789
1790 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1791 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1792 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1793 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1794 else
1795 return isa<TypeDecl>(ND);
1796 }
1797 return false;
1798 }
1799
1800 private:
1801 CXXRecordDecl *ClassDecl;
1802};
1803
1804}
1805
Sebastian Redla74948d2011-09-24 17:48:25 +00001806/// \brief Handle a C++ member initializer.
1807MemInitResult
1808Sema::BuildMemInitializer(Decl *ConstructorD,
1809 Scope *S,
1810 CXXScopeSpec &SS,
1811 IdentifierInfo *MemberOrBase,
1812 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001813 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001814 SourceLocation IdLoc,
1815 const MultiInitializer &Args,
1816 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001817 if (!ConstructorD)
1818 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001819
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001820 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001821
1822 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001823 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001824 if (!Constructor) {
1825 // The user wrote a constructor initializer on a function that is
1826 // not a C++ constructor. Ignore the error for now, because we may
1827 // have more member initializers coming; we'll diagnose it just
1828 // once in ActOnMemInitializers.
1829 return true;
1830 }
1831
1832 CXXRecordDecl *ClassDecl = Constructor->getParent();
1833
1834 // C++ [class.base.init]p2:
1835 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001836 // constructor's class and, if not found in that scope, are looked
1837 // up in the scope containing the constructor's definition.
1838 // [Note: if the constructor's class contains a member with the
1839 // same name as a direct or virtual base class of the class, a
1840 // mem-initializer-id naming the member or base class and composed
1841 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001842 // mem-initializer-id for the hidden base class may be specified
1843 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001844 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001845 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00001846 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001847 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001848 if (Result.first != Result.second) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00001849 ValueDecl *Member;
1850 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1851 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00001852 if (EllipsisLoc.isValid())
1853 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001854 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1855
1856 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001857 }
Francois Pichetd583da02010-12-04 09:14:42 +00001858 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001859 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001860 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001861 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001862 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001863
1864 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001865 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00001866 } else if (DS.getTypeSpecType() == TST_decltype) {
1867 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00001868 } else {
1869 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1870 LookupParsedName(R, S, &SS);
1871
1872 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1873 if (!TyD) {
1874 if (R.isAmbiguous()) return true;
1875
John McCallda6841b2010-04-09 19:01:14 +00001876 // We don't want access-control diagnostics here.
1877 R.suppressDiagnostics();
1878
Douglas Gregora3b624a2010-01-19 06:46:48 +00001879 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1880 bool NotUnknownSpecialization = false;
1881 DeclContext *DC = computeDeclContext(SS, false);
1882 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1883 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1884
1885 if (!NotUnknownSpecialization) {
1886 // When the scope specifier can refer to a member of an unknown
1887 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001888 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1889 SS.getWithLocInContext(Context),
1890 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001891 if (BaseType.isNull())
1892 return true;
1893
Douglas Gregora3b624a2010-01-19 06:46:48 +00001894 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001895 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001896 }
1897 }
1898
Douglas Gregor15e77a22009-12-31 09:10:24 +00001899 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001900 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001901 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001902 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001903 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001904 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001905 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1906 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1907 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001908 // We have found a non-static data member with a similar
1909 // name to what was typed; complain and initialize that
1910 // member.
1911 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1912 << MemberOrBase << true << CorrectedQuotedStr
1913 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1914 Diag(Member->getLocation(), diag::note_previous_decl)
1915 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001916
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001917 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001918 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001919 const CXXBaseSpecifier *DirectBaseSpec;
1920 const CXXBaseSpecifier *VirtualBaseSpec;
1921 if (FindBaseInitializer(*this, ClassDecl,
1922 Context.getTypeDeclType(Type),
1923 DirectBaseSpec, VirtualBaseSpec)) {
1924 // We have found a direct or virtual base class with a
1925 // similar name to what was typed; complain and initialize
1926 // that base class.
1927 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001928 << MemberOrBase << false << CorrectedQuotedStr
1929 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001930
1931 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1932 : VirtualBaseSpec;
1933 Diag(BaseSpec->getSourceRange().getBegin(),
1934 diag::note_base_class_specified_here)
1935 << BaseSpec->getType()
1936 << BaseSpec->getSourceRange();
1937
Douglas Gregor15e77a22009-12-31 09:10:24 +00001938 TyD = Type;
1939 }
1940 }
1941 }
1942
Douglas Gregora3b624a2010-01-19 06:46:48 +00001943 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001944 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla74948d2011-09-24 17:48:25 +00001945 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001946 return true;
1947 }
John McCallb5a0d312009-12-21 10:41:20 +00001948 }
1949
Douglas Gregora3b624a2010-01-19 06:46:48 +00001950 if (BaseType.isNull()) {
1951 BaseType = Context.getTypeDeclType(TyD);
1952 if (SS.isSet()) {
1953 NestedNameSpecifier *Qualifier =
1954 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001955
Douglas Gregora3b624a2010-01-19 06:46:48 +00001956 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001957 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001958 }
John McCallb5a0d312009-12-21 10:41:20 +00001959 }
1960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
John McCallbcd03502009-12-07 02:54:59 +00001962 if (!TInfo)
1963 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001964
Sebastian Redla74948d2011-09-24 17:48:25 +00001965 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001966}
1967
Chandler Carruth599deef2011-09-03 01:14:15 +00001968/// Checks a member initializer expression for cases where reference (or
1969/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001970static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1971 Expr *Init,
1972 SourceLocation IdLoc) {
1973 QualType MemberTy = Member->getType();
1974
1975 // We only handle pointers and references currently.
1976 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1977 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1978 return;
1979
1980 const bool IsPointer = MemberTy->isPointerType();
1981 if (IsPointer) {
1982 if (const UnaryOperator *Op
1983 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1984 // The only case we're worried about with pointers requires taking the
1985 // address.
1986 if (Op->getOpcode() != UO_AddrOf)
1987 return;
1988
1989 Init = Op->getSubExpr();
1990 } else {
1991 // We only handle address-of expression initializers for pointers.
1992 return;
1993 }
1994 }
1995
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001996 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1997 // Taking the address of a temporary will be diagnosed as a hard error.
1998 if (IsPointer)
1999 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002000
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002001 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2002 << Member << Init->getSourceRange();
2003 } else if (const DeclRefExpr *DRE
2004 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2005 // We only warn when referring to a non-reference parameter declaration.
2006 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2007 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002008 return;
2009
2010 S.Diag(Init->getExprLoc(),
2011 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2012 : diag::warn_bind_ref_member_to_parameter)
2013 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002014 } else {
2015 // Other initializers are fine.
2016 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002017 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002018
2019 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2020 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002021}
2022
John McCalle22a04a2009-11-04 23:02:40 +00002023/// Checks an initializer expression for use of uninitialized fields, such as
2024/// containing the field that is being initialized. Returns true if there is an
2025/// uninitialized field was used an updates the SourceLocation parameter; false
2026/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002027static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00002028 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002029 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00002030 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2031
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002032 if (isa<CallExpr>(S)) {
2033 // Do not descend into function calls or constructors, as the use
2034 // of an uninitialized field may be valid. One would have to inspect
2035 // the contents of the function/ctor to determine if it is safe or not.
2036 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2037 // may be safe, depending on what the function/ctor does.
2038 return false;
2039 }
2040 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2041 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002042
2043 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2044 // The member expression points to a static data member.
2045 assert(VD->isStaticDataMember() &&
2046 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00002047 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002048 return false;
2049 }
2050
2051 if (isa<EnumConstantDecl>(RhsField)) {
2052 // The member expression points to an enum.
2053 return false;
2054 }
2055
John McCalle22a04a2009-11-04 23:02:40 +00002056 if (RhsField == LhsField) {
2057 // Initializing a field with itself. Throw a warning.
2058 // But wait; there are exceptions!
2059 // Exception #1: The field may not belong to this record.
2060 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002061 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00002062 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2063 // Even though the field matches, it does not belong to this record.
2064 return false;
2065 }
2066 // None of the exceptions triggered; return true to indicate an
2067 // uninitialized field was used.
2068 *L = ME->getMemberLoc();
2069 return true;
2070 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002071 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00002072 // sizeof/alignof doesn't reference contents, do not warn.
2073 return false;
2074 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2075 // address-of doesn't reference contents (the pointer may be dereferenced
2076 // in the same expression but it would be rare; and weird).
2077 if (UOE->getOpcode() == UO_AddrOf)
2078 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002079 }
John McCall8322c3a2011-02-13 04:07:26 +00002080 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002081 if (!*it) {
2082 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00002083 continue;
2084 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002085 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2086 return true;
John McCalle22a04a2009-11-04 23:02:40 +00002087 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002088 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002089}
2090
John McCallfaf5fb42010-08-26 23:41:50 +00002091MemInitResult
Sebastian Redla74948d2011-09-24 17:48:25 +00002092Sema::BuildMemberInitializer(ValueDecl *Member,
2093 const MultiInitializer &Args,
2094 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002095 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2096 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2097 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002098 "Member must be a FieldDecl or IndirectFieldDecl");
2099
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002100 if (Args.DiagnoseUnexpandedParameterPack(*this))
2101 return true;
2102
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002103 if (Member->isInvalidDecl())
2104 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002105
John McCalle22a04a2009-11-04 23:02:40 +00002106 // Diagnose value-uses of fields to initialize themselves, e.g.
2107 // foo(foo)
2108 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002109 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla74948d2011-09-24 17:48:25 +00002110 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2111 I != E; ++I) {
John McCalle22a04a2009-11-04 23:02:40 +00002112 SourceLocation L;
Sebastian Redla74948d2011-09-24 17:48:25 +00002113 Expr *Arg = *I;
2114 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2115 Arg = DIE->getInit();
2116 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00002117 // FIXME: Return true in the case when other fields are used before being
2118 // uninitialized. For example, let this field be the i'th field. When
2119 // initializing the i'th field, throw a warning if any of the >= i'th
2120 // fields are used, as they are not yet initialized.
2121 // Right now we are only handling the case where the i'th field uses
2122 // itself in its initializer.
2123 Diag(L, diag::warn_field_is_uninit);
2124 }
2125 }
2126
Sebastian Redla74948d2011-09-24 17:48:25 +00002127 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002128
Chandler Carruthd44c3102010-12-06 09:23:57 +00002129 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00002130 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002131 // Can't check initialization for a member of dependent type or when
2132 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002133 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002134
John McCall31168b02011-06-15 23:02:42 +00002135 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002136 } else {
2137 // Initialize the member.
2138 InitializedEntity MemberEntity =
2139 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2140 : InitializedEntity::InitializeMember(IndirectMember, 0);
2141 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002142 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2143 Args.getEndLoc());
John McCallacf0ee52010-10-08 02:01:28 +00002144
Sebastian Redla74948d2011-09-24 17:48:25 +00002145 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002146 if (MemberInit.isInvalid())
2147 return true;
2148
Sebastian Redla74948d2011-09-24 17:48:25 +00002149 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002150
2151 // C++0x [class.base.init]p7:
2152 // The initialization of each base and member constitutes a
2153 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002154 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002155 if (MemberInit.isInvalid())
2156 return true;
2157
2158 // If we are in a dependent context, template instantiation will
2159 // perform this type-checking again. Just save the arguments that we
2160 // received in a ParenListExpr.
2161 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2162 // of the information that we have about the member
2163 // initializer. However, deconstructing the ASTs is a dicey process,
2164 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00002165 if (CurContext->isDependentContext()) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002166 Init = Args.CreateInitExpr(Context,
2167 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00002168 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002169 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00002170 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2171 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002172 }
2173
Chandler Carruthd44c3102010-12-06 09:23:57 +00002174 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002175 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002176 IdLoc, Args.getStartLoc(),
2177 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002178 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00002179 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002180 IdLoc, Args.getStartLoc(),
2181 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002182 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002183}
2184
John McCallfaf5fb42010-08-26 23:41:50 +00002185MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002186Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002187 const MultiInitializer &Args,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002188 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002189 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002190 if (!LangOpts.CPlusPlus0x)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002191 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002192 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002193 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002194
Alexis Huntc5575cc2011-02-26 19:13:13 +00002195 // Initialize the object.
2196 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2197 QualType(ClassDecl->getTypeForDecl(), 0));
2198 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002199 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2200 Args.getEndLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002201
Sebastian Redla74948d2011-09-24 17:48:25 +00002202 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002203 if (DelegationInit.isInvalid())
2204 return true;
2205
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002206 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2207 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002208
Sebastian Redla74948d2011-09-24 17:48:25 +00002209 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002210
2211 // C++0x [class.base.init]p7:
2212 // The initialization of each base and member constitutes a
2213 // full-expression.
2214 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2215 if (DelegationInit.isInvalid())
2216 return true;
2217
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002218 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002219 DelegationInit.takeAs<Expr>(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002220 Args.getEndLoc());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002221}
2222
2223MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002224Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002225 const MultiInitializer &Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002226 CXXRecordDecl *ClassDecl,
2227 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002228 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002229
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002230 SourceLocation BaseLoc
2231 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002232
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002233 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2234 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2235 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2236
2237 // C++ [class.base.init]p2:
2238 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002239 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002240 // of that class, the mem-initializer is ill-formed. A
2241 // mem-initializer-list can initialize a base class using any
2242 // name that denotes that base class type.
2243 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2244
Douglas Gregor44e7df62011-01-04 00:32:56 +00002245 if (EllipsisLoc.isValid()) {
2246 // This is a pack expansion.
2247 if (!BaseType->containsUnexpandedParameterPack()) {
2248 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla74948d2011-09-24 17:48:25 +00002249 << SourceRange(BaseLoc, Args.getEndLoc());
2250
Douglas Gregor44e7df62011-01-04 00:32:56 +00002251 EllipsisLoc = SourceLocation();
2252 }
2253 } else {
2254 // Check for any unexpanded parameter packs.
2255 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2256 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002257
2258 if (Args.DiagnoseUnexpandedParameterPack(*this))
2259 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002260 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002261
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002262 // Check for direct and virtual base classes.
2263 const CXXBaseSpecifier *DirectBaseSpec = 0;
2264 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2265 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002266 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2267 BaseType))
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002268 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002269
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002270 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2271 VirtualBaseSpec);
2272
2273 // C++ [base.class.init]p2:
2274 // Unless the mem-initializer-id names a nonstatic data member of the
2275 // constructor's class or a direct or virtual base of that class, the
2276 // mem-initializer is ill-formed.
2277 if (!DirectBaseSpec && !VirtualBaseSpec) {
2278 // If the class has any dependent bases, then it's possible that
2279 // one of those types will resolve to the same type as
2280 // BaseType. Therefore, just treat this as a dependent base
2281 // class initialization. FIXME: Should we try to check the
2282 // initialization anyway? It seems odd.
2283 if (ClassDecl->hasAnyDependentBases())
2284 Dependent = true;
2285 else
2286 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2287 << BaseType << Context.getTypeDeclType(ClassDecl)
2288 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2289 }
2290 }
2291
2292 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002293 // Can't check initialization for a base of dependent type or when
2294 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002295 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002296
John McCall31168b02011-06-15 23:02:42 +00002297 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002298
Sebastian Redla74948d2011-09-24 17:48:25 +00002299 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2300 /*IsVirtual=*/false,
2301 Args.getStartLoc(), BaseInit,
2302 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002303 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002304
2305 // C++ [base.class.init]p2:
2306 // If a mem-initializer-id is ambiguous because it designates both
2307 // a direct non-virtual base class and an inherited virtual base
2308 // class, the mem-initializer is ill-formed.
2309 if (DirectBaseSpec && VirtualBaseSpec)
2310 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002311 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002312
2313 CXXBaseSpecifier *BaseSpec
2314 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2315 if (!BaseSpec)
2316 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2317
2318 // Initialize the base.
2319 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00002320 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002321 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002322 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2323 Args.getEndLoc());
2324
2325 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002326 if (BaseInit.isInvalid())
2327 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002328
Sebastian Redla74948d2011-09-24 17:48:25 +00002329 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2330
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002331 // C++0x [class.base.init]p7:
2332 // The initialization of each base and member constitutes a
2333 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002334 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002335 if (BaseInit.isInvalid())
2336 return true;
2337
2338 // If we are in a dependent context, template instantiation will
2339 // perform this type-checking again. Just save the arguments that we
2340 // received in a ParenListExpr.
2341 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2342 // of the information that we have about the base
2343 // initializer. However, deconstructing the ASTs is a dicey process,
2344 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002345 if (CurContext->isDependentContext())
2346 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002347
Alexis Hunt1d792652011-01-08 20:30:50 +00002348 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002349 BaseSpec->isVirtual(),
2350 Args.getStartLoc(),
2351 BaseInit.takeAs<Expr>(),
2352 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002353}
2354
Sebastian Redl22653ba2011-08-30 19:58:05 +00002355// Create a static_cast\<T&&>(expr).
2356static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2357 QualType ExprType = E->getType();
2358 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2359 SourceLocation ExprLoc = E->getLocStart();
2360 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2361 TargetType, ExprLoc);
2362
2363 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2364 SourceRange(ExprLoc, ExprLoc),
2365 E->getSourceRange()).take();
2366}
2367
Anders Carlsson1b00e242010-04-23 03:10:23 +00002368/// ImplicitInitializerKind - How an implicit base or member initializer should
2369/// initialize its base or member.
2370enum ImplicitInitializerKind {
2371 IIK_Default,
2372 IIK_Copy,
2373 IIK_Move
2374};
2375
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002376static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002377BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002378 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002379 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002380 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002381 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002382 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002383 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2384 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002385
John McCalldadc5752010-08-24 06:29:42 +00002386 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002387
2388 switch (ImplicitInitKind) {
2389 case IIK_Default: {
2390 InitializationKind InitKind
2391 = InitializationKind::CreateDefault(Constructor->getLocation());
2392 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2393 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002394 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002395 break;
2396 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002397
Sebastian Redl22653ba2011-08-30 19:58:05 +00002398 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002399 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002400 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002401 ParmVarDecl *Param = Constructor->getParamDecl(0);
2402 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00002403
Anders Carlsson1b00e242010-04-23 03:10:23 +00002404 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002405 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2406 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002407 Constructor->getLocation(), ParamType,
2408 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002409
Eli Friedmanfa0df832012-02-02 03:46:19 +00002410 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2411
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002412 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002413 QualType ArgTy =
2414 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2415 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002416
Sebastian Redl22653ba2011-08-30 19:58:05 +00002417 if (Moving) {
2418 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2419 }
2420
John McCallcf142162010-08-07 06:22:56 +00002421 CXXCastPath BasePath;
2422 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002423 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2424 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002425 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002426 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002427
Anders Carlsson1b00e242010-04-23 03:10:23 +00002428 InitializationKind InitKind
2429 = InitializationKind::CreateDirect(Constructor->getLocation(),
2430 SourceLocation(), SourceLocation());
2431 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2432 &CopyCtorArg, 1);
2433 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002434 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002435 break;
2436 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002437 }
John McCallb268a282010-08-23 23:25:46 +00002438
Douglas Gregora40433a2010-12-07 00:41:46 +00002439 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002440 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002441 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002442
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002443 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002444 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002445 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2446 SourceLocation()),
2447 BaseSpec->isVirtual(),
2448 SourceLocation(),
2449 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002450 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002451 SourceLocation());
2452
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002453 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002454}
2455
Sebastian Redl22653ba2011-08-30 19:58:05 +00002456static bool RefersToRValueRef(Expr *MemRef) {
2457 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2458 return Referenced->getType()->isRValueReferenceType();
2459}
2460
Anders Carlsson3c1db572010-04-23 02:15:47 +00002461static bool
2462BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002463 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002464 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002465 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002466 if (Field->isInvalidDecl())
2467 return true;
2468
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002469 SourceLocation Loc = Constructor->getLocation();
2470
Sebastian Redl22653ba2011-08-30 19:58:05 +00002471 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2472 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002473 ParmVarDecl *Param = Constructor->getParamDecl(0);
2474 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002475
2476 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00002477 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2478 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002479
Anders Carlsson423f5d82010-04-23 16:04:08 +00002480 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002481 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2482 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002483 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002484
Eli Friedmanfa0df832012-02-02 03:46:19 +00002485 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2486
Sebastian Redl22653ba2011-08-30 19:58:05 +00002487 if (Moving) {
2488 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2489 }
2490
Douglas Gregor94f9a482010-05-05 05:51:00 +00002491 // Build a reference to this field within the parameter.
2492 CXXScopeSpec SS;
2493 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2494 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002495 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2496 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002497 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002498 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002499 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002500 ParamType, Loc,
2501 /*IsArrow=*/false,
2502 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002503 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002504 /*FirstQualifierInScope=*/0,
2505 MemberLookup,
2506 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002507 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002508 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002509
2510 // C++11 [class.copy]p15:
2511 // - if a member m has rvalue reference type T&&, it is direct-initialized
2512 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002513 if (RefersToRValueRef(CtorArg.get())) {
2514 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002515 }
2516
Douglas Gregor94f9a482010-05-05 05:51:00 +00002517 // When the field we are copying is an array, create index variables for
2518 // each dimension of the array. We use these index variables to subscript
2519 // the source array, and other clients (e.g., CodeGen) will perform the
2520 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002521 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002522 QualType BaseType = Field->getType();
2523 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002524 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002525 while (const ConstantArrayType *Array
2526 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002527 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002528 // Create the iteration variable for this array index.
2529 IdentifierInfo *IterationVarName = 0;
2530 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002531 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002532 llvm::raw_svector_ostream OS(Str);
2533 OS << "__i" << IndexVariables.size();
2534 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2535 }
2536 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002537 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002538 IterationVarName, SizeType,
2539 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002540 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002541 IndexVariables.push_back(IterationVar);
2542
2543 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002544 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00002545 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002546 assert(!IterationVarRef.isInvalid() &&
2547 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00002548 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2549 assert(!IterationVarRef.isInvalid() &&
2550 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002551
Douglas Gregor94f9a482010-05-05 05:51:00 +00002552 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002553 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002554 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002555 Loc);
2556 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002557 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002558
Douglas Gregor94f9a482010-05-05 05:51:00 +00002559 BaseType = Array->getElementType();
2560 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002561
2562 // The array subscript expression is an lvalue, which is wrong for moving.
2563 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002564 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002565
Douglas Gregor94f9a482010-05-05 05:51:00 +00002566 // Construct the entity that we will be initializing. For an array, this
2567 // will be first element in the array, which may require several levels
2568 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002569 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002570 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002571 if (Indirect)
2572 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2573 else
2574 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002575 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2576 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2577 0,
2578 Entities.back()));
2579
2580 // Direct-initialize to use the copy constructor.
2581 InitializationKind InitKind =
2582 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2583
Sebastian Redle9c4e842011-09-04 18:14:28 +00002584 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002585 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002586 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002587
John McCalldadc5752010-08-24 06:29:42 +00002588 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002589 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002590 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002591 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002592 if (MemberInit.isInvalid())
2593 return true;
2594
Douglas Gregor493627b2011-08-10 15:22:55 +00002595 if (Indirect) {
2596 assert(IndexVariables.size() == 0 &&
2597 "Indirect field improperly initialized");
2598 CXXMemberInit
2599 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2600 Loc, Loc,
2601 MemberInit.takeAs<Expr>(),
2602 Loc);
2603 } else
2604 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2605 Loc, MemberInit.takeAs<Expr>(),
2606 Loc,
2607 IndexVariables.data(),
2608 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002609 return false;
2610 }
2611
Anders Carlsson423f5d82010-04-23 16:04:08 +00002612 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2613
Anders Carlsson3c1db572010-04-23 02:15:47 +00002614 QualType FieldBaseElementType =
2615 SemaRef.Context.getBaseElementType(Field->getType());
2616
Anders Carlsson3c1db572010-04-23 02:15:47 +00002617 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002618 InitializedEntity InitEntity
2619 = Indirect? InitializedEntity::InitializeMember(Indirect)
2620 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002621 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002622 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002623
2624 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002625 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002626 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002627
Douglas Gregora40433a2010-12-07 00:41:46 +00002628 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002629 if (MemberInit.isInvalid())
2630 return true;
2631
Douglas Gregor493627b2011-08-10 15:22:55 +00002632 if (Indirect)
2633 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2634 Indirect, Loc,
2635 Loc,
2636 MemberInit.get(),
2637 Loc);
2638 else
2639 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2640 Field, Loc, Loc,
2641 MemberInit.get(),
2642 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002643 return false;
2644 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002645
Alexis Hunt8b455182011-05-17 00:19:05 +00002646 if (!Field->getParent()->isUnion()) {
2647 if (FieldBaseElementType->isReferenceType()) {
2648 SemaRef.Diag(Constructor->getLocation(),
2649 diag::err_uninitialized_member_in_ctor)
2650 << (int)Constructor->isImplicit()
2651 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2652 << 0 << Field->getDeclName();
2653 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2654 return true;
2655 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002656
Alexis Hunt8b455182011-05-17 00:19:05 +00002657 if (FieldBaseElementType.isConstQualified()) {
2658 SemaRef.Diag(Constructor->getLocation(),
2659 diag::err_uninitialized_member_in_ctor)
2660 << (int)Constructor->isImplicit()
2661 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2662 << 1 << Field->getDeclName();
2663 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2664 return true;
2665 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002666 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002667
John McCall31168b02011-06-15 23:02:42 +00002668 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2669 FieldBaseElementType->isObjCRetainableType() &&
2670 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2671 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2672 // Instant objects:
2673 // Default-initialize Objective-C pointers to NULL.
2674 CXXMemberInit
2675 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2676 Loc, Loc,
2677 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2678 Loc);
2679 return false;
2680 }
2681
Anders Carlsson3c1db572010-04-23 02:15:47 +00002682 // Nothing to initialize.
2683 CXXMemberInit = 0;
2684 return false;
2685}
John McCallbc83b3f2010-05-20 23:23:51 +00002686
2687namespace {
2688struct BaseAndFieldInfo {
2689 Sema &S;
2690 CXXConstructorDecl *Ctor;
2691 bool AnyErrorsInInits;
2692 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002693 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002694 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002695
2696 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2697 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002698 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2699 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002700 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002701 else if (Generated && Ctor->isMoveConstructor())
2702 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002703 else
2704 IIK = IIK_Default;
2705 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00002706
2707 bool isImplicitCopyOrMove() const {
2708 switch (IIK) {
2709 case IIK_Copy:
2710 case IIK_Move:
2711 return true;
2712
2713 case IIK_Default:
2714 return false;
2715 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002716
2717 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00002718 }
John McCallbc83b3f2010-05-20 23:23:51 +00002719};
2720}
2721
Richard Smithc94ec842011-09-19 13:34:43 +00002722/// \brief Determine whether the given indirect field declaration is somewhere
2723/// within an anonymous union.
2724static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2725 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2726 CEnd = F->chain_end();
2727 C != CEnd; ++C)
2728 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2729 if (Record->isUnion())
2730 return true;
2731
2732 return false;
2733}
2734
Douglas Gregor10f939c2011-11-02 23:04:16 +00002735/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2736/// array type.
2737static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2738 if (T->isIncompleteArrayType())
2739 return true;
2740
2741 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2742 if (!ArrayT->getSize())
2743 return true;
2744
2745 T = ArrayT->getElementType();
2746 }
2747
2748 return false;
2749}
2750
Richard Smith938f40b2011-06-11 17:19:42 +00002751static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002752 FieldDecl *Field,
2753 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002754
Chandler Carruth139e9622010-06-30 02:59:29 +00002755 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002756 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002757 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002758 return false;
2759 }
2760
Richard Smith938f40b2011-06-11 17:19:42 +00002761 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2762 // has a brace-or-equal-initializer, the entity is initialized as specified
2763 // in [dcl.init].
Douglas Gregor7db3e952011-11-28 20:03:15 +00002764 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002765 CXXCtorInitializer *Init;
2766 if (Indirect)
2767 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2768 SourceLocation(),
2769 SourceLocation(), 0,
2770 SourceLocation());
2771 else
2772 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2773 SourceLocation(),
2774 SourceLocation(), 0,
2775 SourceLocation());
2776 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002777 return false;
2778 }
2779
Richard Smith12d5ed82011-09-18 11:14:50 +00002780 // Don't build an implicit initializer for union members if none was
2781 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002782 if (Field->getParent()->isUnion() ||
2783 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002784 return false;
2785
Douglas Gregor10f939c2011-11-02 23:04:16 +00002786 // Don't initialize incomplete or zero-length arrays.
2787 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2788 return false;
2789
John McCallbc83b3f2010-05-20 23:23:51 +00002790 // Don't try to build an implicit initializer if there were semantic
2791 // errors in any of the initializers (and therefore we might be
2792 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002793 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002794 return false;
2795
Alexis Hunt1d792652011-01-08 20:30:50 +00002796 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002797 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2798 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002799 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002800
Francois Pichetd583da02010-12-04 09:14:42 +00002801 if (Init)
2802 Info.AllToInit.push_back(Init);
2803
John McCallbc83b3f2010-05-20 23:23:51 +00002804 return false;
2805}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002806
2807bool
2808Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2809 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002810 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002811 Constructor->setNumCtorInitializers(1);
2812 CXXCtorInitializer **initializer =
2813 new (Context) CXXCtorInitializer*[1];
2814 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2815 Constructor->setCtorInitializers(initializer);
2816
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002817 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002818 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002819 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2820 }
2821
Alexis Hunte2622992011-05-05 00:05:47 +00002822 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002823
Alexis Hunt61bc1732011-05-01 07:04:31 +00002824 return false;
2825}
Douglas Gregor493627b2011-08-10 15:22:55 +00002826
John McCall1b1a1db2011-06-17 00:18:42 +00002827bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2828 CXXCtorInitializer **Initializers,
2829 unsigned NumInitializers,
2830 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002831 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002832 // Just store the initializers as written, they will be checked during
2833 // instantiation.
2834 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002835 Constructor->setNumCtorInitializers(NumInitializers);
2836 CXXCtorInitializer **baseOrMemberInitializers =
2837 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002838 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002839 NumInitializers * sizeof(CXXCtorInitializer*));
2840 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002841 }
2842
2843 return false;
2844 }
2845
John McCallbc83b3f2010-05-20 23:23:51 +00002846 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002847
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002848 // We need to build the initializer AST according to order of construction
2849 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002850 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002851 if (!ClassDecl)
2852 return true;
2853
Eli Friedman9cf6b592009-11-09 19:20:36 +00002854 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002855
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002856 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002857 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002858
2859 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002860 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002861 else
Francois Pichetd583da02010-12-04 09:14:42 +00002862 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002863 }
2864
Anders Carlsson43c64af2010-04-21 19:52:01 +00002865 // Keep track of the direct virtual bases.
2866 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2867 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2868 E = ClassDecl->bases_end(); I != E; ++I) {
2869 if (I->isVirtual())
2870 DirectVBases.insert(I);
2871 }
2872
Anders Carlssondb0a9652010-04-02 06:26:44 +00002873 // Push virtual bases before others.
2874 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2875 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2876
Alexis Hunt1d792652011-01-08 20:30:50 +00002877 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002878 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2879 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002880 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002881 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002882 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002883 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002884 VBase, IsInheritedVirtualBase,
2885 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002886 HadError = true;
2887 continue;
2888 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002889
John McCallbc83b3f2010-05-20 23:23:51 +00002890 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002891 }
2892 }
Mike Stump11289f42009-09-09 15:08:12 +00002893
John McCallbc83b3f2010-05-20 23:23:51 +00002894 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002895 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2896 E = ClassDecl->bases_end(); Base != E; ++Base) {
2897 // Virtuals are in the virtual base list and already constructed.
2898 if (Base->isVirtual())
2899 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002900
Alexis Hunt1d792652011-01-08 20:30:50 +00002901 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002902 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2903 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002904 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002905 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002906 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002907 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002908 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002909 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002910 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002911 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002912
John McCallbc83b3f2010-05-20 23:23:51 +00002913 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002914 }
2915 }
Mike Stump11289f42009-09-09 15:08:12 +00002916
John McCallbc83b3f2010-05-20 23:23:51 +00002917 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002918 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2919 MemEnd = ClassDecl->decls_end();
2920 Mem != MemEnd; ++Mem) {
2921 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00002922 // C++ [class.bit]p2:
2923 // A declaration for a bit-field that omits the identifier declares an
2924 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2925 // initialized.
2926 if (F->isUnnamedBitfield())
2927 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002928
Sebastian Redl22653ba2011-08-30 19:58:05 +00002929 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002930 // handle anonymous struct/union fields based on their individual
2931 // indirect fields.
2932 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2933 continue;
2934
2935 if (CollectFieldInitializer(*this, Info, F))
2936 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002937 continue;
2938 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002939
2940 // Beyond this point, we only consider default initialization.
2941 if (Info.IIK != IIK_Default)
2942 continue;
2943
2944 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2945 if (F->getType()->isIncompleteArrayType()) {
2946 assert(ClassDecl->hasFlexibleArrayMember() &&
2947 "Incomplete array type is not valid");
2948 continue;
2949 }
2950
Douglas Gregor493627b2011-08-10 15:22:55 +00002951 // Initialize each field of an anonymous struct individually.
2952 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2953 HadError = true;
2954
2955 continue;
2956 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002957 }
Mike Stump11289f42009-09-09 15:08:12 +00002958
John McCallbc83b3f2010-05-20 23:23:51 +00002959 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002960 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002961 Constructor->setNumCtorInitializers(NumInitializers);
2962 CXXCtorInitializer **baseOrMemberInitializers =
2963 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002964 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002965 NumInitializers * sizeof(CXXCtorInitializer*));
2966 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002967
John McCalla6309952010-03-16 21:39:52 +00002968 // Constructors implicitly reference the base and member
2969 // destructors.
2970 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2971 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002972 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002973
2974 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002975}
2976
Eli Friedman952c15d2009-07-21 19:28:10 +00002977static void *GetKeyForTopLevelField(FieldDecl *Field) {
2978 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002979 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002980 if (RT->getDecl()->isAnonymousStructOrUnion())
2981 return static_cast<void *>(RT->getDecl());
2982 }
2983 return static_cast<void *>(Field);
2984}
2985
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002986static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002987 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002988}
2989
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002990static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002991 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002992 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002993 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002994
Eli Friedman952c15d2009-07-21 19:28:10 +00002995 // For fields injected into the class via declaration of an anonymous union,
2996 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002997 FieldDecl *Field = Member->getAnyMember();
2998
John McCall23eebd92010-04-10 09:28:51 +00002999 // If the field is a member of an anonymous struct or union, our key
3000 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00003001 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003002 if (RD->isAnonymousStructOrUnion()) {
3003 while (true) {
3004 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3005 if (Parent->isAnonymousStructOrUnion())
3006 RD = Parent;
3007 else
3008 break;
3009 }
3010
Anders Carlsson83ac3122010-03-30 16:19:37 +00003011 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00003012 }
Mike Stump11289f42009-09-09 15:08:12 +00003013
Anders Carlssona942dcd2010-03-30 15:39:27 +00003014 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003015}
3016
Anders Carlssone857b292010-04-02 03:37:03 +00003017static void
3018DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003019 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00003020 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00003021 unsigned NumInits) {
3022 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003023 return;
Mike Stump11289f42009-09-09 15:08:12 +00003024
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003025 // Don't check initializers order unless the warning is enabled at the
3026 // location of at least one initializer.
3027 bool ShouldCheckOrder = false;
3028 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003029 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003030 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3031 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003032 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003033 ShouldCheckOrder = true;
3034 break;
3035 }
3036 }
3037 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003038 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003039
John McCallbb7b6582010-04-10 07:37:23 +00003040 // Build the list of bases and members in the order that they'll
3041 // actually be initialized. The explicit initializers should be in
3042 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003043 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003044
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003045 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3046
John McCallbb7b6582010-04-10 07:37:23 +00003047 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003048 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003049 ClassDecl->vbases_begin(),
3050 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003051 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003052
John McCallbb7b6582010-04-10 07:37:23 +00003053 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003054 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003055 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003056 if (Base->isVirtual())
3057 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003058 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003059 }
Mike Stump11289f42009-09-09 15:08:12 +00003060
John McCallbb7b6582010-04-10 07:37:23 +00003061 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003062 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003063 E = ClassDecl->field_end(); Field != E; ++Field) {
3064 if (Field->isUnnamedBitfield())
3065 continue;
3066
John McCallbb7b6582010-04-10 07:37:23 +00003067 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregor556e5862011-10-10 17:22:13 +00003068 }
3069
John McCallbb7b6582010-04-10 07:37:23 +00003070 unsigned NumIdealInits = IdealInitKeys.size();
3071 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003072
Alexis Hunt1d792652011-01-08 20:30:50 +00003073 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00003074 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003075 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00003076 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003077
3078 // Scan forward to try to find this initializer in the idealized
3079 // initializers list.
3080 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3081 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003082 break;
John McCallbb7b6582010-04-10 07:37:23 +00003083
3084 // If we didn't find this initializer, it must be because we
3085 // scanned past it on a previous iteration. That can only
3086 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003087 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003088 Sema::SemaDiagnosticBuilder D =
3089 SemaRef.Diag(PrevInit->getSourceLocation(),
3090 diag::warn_initializer_out_of_order);
3091
Francois Pichetd583da02010-12-04 09:14:42 +00003092 if (PrevInit->isAnyMemberInitializer())
3093 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003094 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003095 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003096
Francois Pichetd583da02010-12-04 09:14:42 +00003097 if (Init->isAnyMemberInitializer())
3098 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003099 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003100 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003101
3102 // Move back to the initializer's location in the ideal list.
3103 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3104 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003105 break;
John McCallbb7b6582010-04-10 07:37:23 +00003106
3107 assert(IdealIndex != NumIdealInits &&
3108 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003109 }
John McCallbb7b6582010-04-10 07:37:23 +00003110
3111 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003112 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003113}
3114
John McCall23eebd92010-04-10 09:28:51 +00003115namespace {
3116bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003117 CXXCtorInitializer *Init,
3118 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003119 if (!PrevInit) {
3120 PrevInit = Init;
3121 return false;
3122 }
3123
3124 if (FieldDecl *Field = Init->getMember())
3125 S.Diag(Init->getSourceLocation(),
3126 diag::err_multiple_mem_initialization)
3127 << Field->getDeclName()
3128 << Init->getSourceRange();
3129 else {
John McCall424cec92011-01-19 06:33:43 +00003130 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003131 assert(BaseClass && "neither field nor base");
3132 S.Diag(Init->getSourceLocation(),
3133 diag::err_multiple_base_initialization)
3134 << QualType(BaseClass, 0)
3135 << Init->getSourceRange();
3136 }
3137 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3138 << 0 << PrevInit->getSourceRange();
3139
3140 return true;
3141}
3142
Alexis Hunt1d792652011-01-08 20:30:50 +00003143typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003144typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3145
3146bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003147 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003148 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003149 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003150 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003151 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003152
3153 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003154 if (Parent->isUnion()) {
3155 UnionEntry &En = Unions[Parent];
3156 if (En.first && En.first != Child) {
3157 S.Diag(Init->getSourceLocation(),
3158 diag::err_multiple_mem_union_initialization)
3159 << Field->getDeclName()
3160 << Init->getSourceRange();
3161 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3162 << 0 << En.second->getSourceRange();
3163 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003164 }
3165 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003166 En.first = Child;
3167 En.second = Init;
3168 }
David Blaikie0f65d592011-11-17 06:01:57 +00003169 if (!Parent->isAnonymousStructOrUnion())
3170 return false;
John McCall23eebd92010-04-10 09:28:51 +00003171 }
3172
3173 Child = Parent;
3174 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003175 }
John McCall23eebd92010-04-10 09:28:51 +00003176
3177 return false;
3178}
3179}
3180
Anders Carlssone857b292010-04-02 03:37:03 +00003181/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003182void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003183 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00003184 CXXCtorInitializer **meminits,
3185 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003186 bool AnyErrors) {
3187 if (!ConstructorDecl)
3188 return;
3189
3190 AdjustDeclIfTemplate(ConstructorDecl);
3191
3192 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003193 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003194
3195 if (!Constructor) {
3196 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3197 return;
3198 }
3199
Alexis Hunt1d792652011-01-08 20:30:50 +00003200 CXXCtorInitializer **MemInits =
3201 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00003202
3203 // Mapping for the duplicate initializers check.
3204 // For member initializers, this is keyed with a FieldDecl*.
3205 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003206 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003207
3208 // Mapping for the inconsistent anonymous-union initializers check.
3209 RedundantUnionMap MemberUnions;
3210
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003211 bool HadError = false;
3212 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003213 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003214
Abramo Bagnara341d7832010-05-26 18:09:23 +00003215 // Set the source order index.
3216 Init->setSourceOrder(i);
3217
Francois Pichetd583da02010-12-04 09:14:42 +00003218 if (Init->isAnyMemberInitializer()) {
3219 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003220 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3221 CheckRedundantUnionInit(*this, Init, MemberUnions))
3222 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003223 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003224 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3225 if (CheckRedundantInit(*this, Init, Members[Key]))
3226 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003227 } else {
3228 assert(Init->isDelegatingInitializer());
3229 // This must be the only initializer
3230 if (i != 0 || NumMemInits > 1) {
3231 Diag(MemInits[0]->getSourceLocation(),
3232 diag::err_delegating_initializer_alone)
3233 << MemInits[0]->getSourceRange();
3234 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00003235 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003236 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003237 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003238 // Return immediately as the initializer is set.
3239 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003240 }
Anders Carlssone857b292010-04-02 03:37:03 +00003241 }
3242
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003243 if (HadError)
3244 return;
3245
Anders Carlssone857b292010-04-02 03:37:03 +00003246 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003247
Alexis Hunt1d792652011-01-08 20:30:50 +00003248 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00003249}
3250
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003251void
John McCalla6309952010-03-16 21:39:52 +00003252Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3253 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003254 // Ignore dependent contexts. Also ignore unions, since their members never
3255 // have destructors implicitly called.
3256 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003257 return;
John McCall1064d7e2010-03-16 05:22:47 +00003258
3259 // FIXME: all the access-control diagnostics are positioned on the
3260 // field/base declaration. That's probably good; that said, the
3261 // user might reasonably want to know why the destructor is being
3262 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003263
Anders Carlssondee9a302009-11-17 04:44:12 +00003264 // Non-static data members.
3265 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3266 E = ClassDecl->field_end(); I != E; ++I) {
3267 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003268 if (Field->isInvalidDecl())
3269 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003270
3271 // Don't destroy incomplete or zero-length arrays.
3272 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3273 continue;
3274
Anders Carlssondee9a302009-11-17 04:44:12 +00003275 QualType FieldType = Context.getBaseElementType(Field->getType());
3276
3277 const RecordType* RT = FieldType->getAs<RecordType>();
3278 if (!RT)
3279 continue;
3280
3281 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003282 if (FieldClassDecl->isInvalidDecl())
3283 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003284 if (FieldClassDecl->hasTrivialDestructor())
3285 continue;
3286
Douglas Gregore71edda2010-07-01 22:47:18 +00003287 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003288 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003289 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003290 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003291 << Field->getDeclName()
3292 << FieldType);
3293
Eli Friedmanfa0df832012-02-02 03:46:19 +00003294 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003295 }
3296
John McCall1064d7e2010-03-16 05:22:47 +00003297 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3298
Anders Carlssondee9a302009-11-17 04:44:12 +00003299 // Bases.
3300 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3301 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003302 // Bases are always records in a well-formed non-dependent class.
3303 const RecordType *RT = Base->getType()->getAs<RecordType>();
3304
3305 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003306 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003307 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003308
John McCall1064d7e2010-03-16 05:22:47 +00003309 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003310 // If our base class is invalid, we probably can't get its dtor anyway.
3311 if (BaseClassDecl->isInvalidDecl())
3312 continue;
3313 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00003314 if (BaseClassDecl->hasTrivialDestructor())
3315 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003316
Douglas Gregore71edda2010-07-01 22:47:18 +00003317 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003318 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003319
3320 // FIXME: caret should be on the start of the class name
3321 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003322 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003323 << Base->getType()
3324 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00003325
Eli Friedmanfa0df832012-02-02 03:46:19 +00003326 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003327 }
3328
3329 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003330 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3331 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003332
3333 // Bases are always records in a well-formed non-dependent class.
3334 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3335
3336 // Ignore direct virtual bases.
3337 if (DirectVirtualBases.count(RT))
3338 continue;
3339
John McCall1064d7e2010-03-16 05:22:47 +00003340 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003341 // If our base class is invalid, we probably can't get its dtor anyway.
3342 if (BaseClassDecl->isInvalidDecl())
3343 continue;
3344 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003345 if (BaseClassDecl->hasTrivialDestructor())
3346 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003347
Douglas Gregore71edda2010-07-01 22:47:18 +00003348 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003349 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003350 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003351 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00003352 << VBase->getType());
3353
Eli Friedmanfa0df832012-02-02 03:46:19 +00003354 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003355 }
3356}
3357
John McCall48871652010-08-21 09:40:31 +00003358void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003359 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003360 return;
Mike Stump11289f42009-09-09 15:08:12 +00003361
Mike Stump11289f42009-09-09 15:08:12 +00003362 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003363 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00003364 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003365}
3366
Mike Stump11289f42009-09-09 15:08:12 +00003367bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003368 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00003369 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00003370 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00003371 else
John McCall02db245d2010-08-18 09:41:07 +00003372 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00003373}
3374
Anders Carlssoneabf7702009-08-27 00:13:57 +00003375bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003376 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003377 if (!getLangOptions().CPlusPlus)
3378 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003379
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003380 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00003381 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00003382
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003383 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003384 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003385 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003386 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003387
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003388 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00003389 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003392 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003393 if (!RT)
3394 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003395
John McCall67da35c2010-02-04 22:26:26 +00003396 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003397
John McCall02db245d2010-08-18 09:41:07 +00003398 // We can't answer whether something is abstract until it has a
3399 // definition. If it's currently being defined, we'll walk back
3400 // over all the declarations when we have a full definition.
3401 const CXXRecordDecl *Def = RD->getDefinition();
3402 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003403 return false;
3404
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003405 if (!RD->isAbstract())
3406 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003407
Anders Carlssoneabf7702009-08-27 00:13:57 +00003408 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00003409 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003410
John McCall02db245d2010-08-18 09:41:07 +00003411 return true;
3412}
3413
3414void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3415 // Check if we've already emitted the list of pure virtual functions
3416 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003417 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003418 return;
Mike Stump11289f42009-09-09 15:08:12 +00003419
Douglas Gregor4165bd62010-03-23 23:47:56 +00003420 CXXFinalOverriderMap FinalOverriders;
3421 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003422
Anders Carlssona2f74f32010-06-03 01:00:02 +00003423 // Keep a set of seen pure methods so we won't diagnose the same method
3424 // more than once.
3425 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3426
Douglas Gregor4165bd62010-03-23 23:47:56 +00003427 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3428 MEnd = FinalOverriders.end();
3429 M != MEnd;
3430 ++M) {
3431 for (OverridingMethods::iterator SO = M->second.begin(),
3432 SOEnd = M->second.end();
3433 SO != SOEnd; ++SO) {
3434 // C++ [class.abstract]p4:
3435 // A class is abstract if it contains or inherits at least one
3436 // pure virtual function for which the final overrider is pure
3437 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003438
Douglas Gregor4165bd62010-03-23 23:47:56 +00003439 //
3440 if (SO->second.size() != 1)
3441 continue;
3442
3443 if (!SO->second.front().Method->isPure())
3444 continue;
3445
Anders Carlssona2f74f32010-06-03 01:00:02 +00003446 if (!SeenPureMethods.insert(SO->second.front().Method))
3447 continue;
3448
Douglas Gregor4165bd62010-03-23 23:47:56 +00003449 Diag(SO->second.front().Method->getLocation(),
3450 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003451 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003452 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003453 }
3454
3455 if (!PureVirtualClassDiagSet)
3456 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3457 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003458}
3459
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003460namespace {
John McCall02db245d2010-08-18 09:41:07 +00003461struct AbstractUsageInfo {
3462 Sema &S;
3463 CXXRecordDecl *Record;
3464 CanQualType AbstractType;
3465 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003466
John McCall02db245d2010-08-18 09:41:07 +00003467 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3468 : S(S), Record(Record),
3469 AbstractType(S.Context.getCanonicalType(
3470 S.Context.getTypeDeclType(Record))),
3471 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003472
John McCall02db245d2010-08-18 09:41:07 +00003473 void DiagnoseAbstractType() {
3474 if (Invalid) return;
3475 S.DiagnoseAbstractType(Record);
3476 Invalid = true;
3477 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003478
John McCall02db245d2010-08-18 09:41:07 +00003479 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3480};
3481
3482struct CheckAbstractUsage {
3483 AbstractUsageInfo &Info;
3484 const NamedDecl *Ctx;
3485
3486 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3487 : Info(Info), Ctx(Ctx) {}
3488
3489 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3490 switch (TL.getTypeLocClass()) {
3491#define ABSTRACT_TYPELOC(CLASS, PARENT)
3492#define TYPELOC(CLASS, PARENT) \
3493 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3494#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003495 }
John McCall02db245d2010-08-18 09:41:07 +00003496 }
Mike Stump11289f42009-09-09 15:08:12 +00003497
John McCall02db245d2010-08-18 09:41:07 +00003498 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3499 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3500 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003501 if (!TL.getArg(I))
3502 continue;
3503
John McCall02db245d2010-08-18 09:41:07 +00003504 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3505 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003506 }
John McCall02db245d2010-08-18 09:41:07 +00003507 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003508
John McCall02db245d2010-08-18 09:41:07 +00003509 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3510 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3511 }
Mike Stump11289f42009-09-09 15:08:12 +00003512
John McCall02db245d2010-08-18 09:41:07 +00003513 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3514 // Visit the type parameters from a permissive context.
3515 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3516 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3517 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3518 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3519 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3520 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003521 }
John McCall02db245d2010-08-18 09:41:07 +00003522 }
Mike Stump11289f42009-09-09 15:08:12 +00003523
John McCall02db245d2010-08-18 09:41:07 +00003524 // Visit pointee types from a permissive context.
3525#define CheckPolymorphic(Type) \
3526 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3527 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3528 }
3529 CheckPolymorphic(PointerTypeLoc)
3530 CheckPolymorphic(ReferenceTypeLoc)
3531 CheckPolymorphic(MemberPointerTypeLoc)
3532 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00003533 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003534
John McCall02db245d2010-08-18 09:41:07 +00003535 /// Handle all the types we haven't given a more specific
3536 /// implementation for above.
3537 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3538 // Every other kind of type that we haven't called out already
3539 // that has an inner type is either (1) sugar or (2) contains that
3540 // inner type in some way as a subobject.
3541 if (TypeLoc Next = TL.getNextTypeLoc())
3542 return Visit(Next, Sel);
3543
3544 // If there's no inner type and we're in a permissive context,
3545 // don't diagnose.
3546 if (Sel == Sema::AbstractNone) return;
3547
3548 // Check whether the type matches the abstract type.
3549 QualType T = TL.getType();
3550 if (T->isArrayType()) {
3551 Sel = Sema::AbstractArrayType;
3552 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003553 }
John McCall02db245d2010-08-18 09:41:07 +00003554 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3555 if (CT != Info.AbstractType) return;
3556
3557 // It matched; do some magic.
3558 if (Sel == Sema::AbstractArrayType) {
3559 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3560 << T << TL.getSourceRange();
3561 } else {
3562 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3563 << Sel << T << TL.getSourceRange();
3564 }
3565 Info.DiagnoseAbstractType();
3566 }
3567};
3568
3569void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3570 Sema::AbstractDiagSelID Sel) {
3571 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3572}
3573
3574}
3575
3576/// Check for invalid uses of an abstract type in a method declaration.
3577static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3578 CXXMethodDecl *MD) {
3579 // No need to do the check on definitions, which require that
3580 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003581 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003582 return;
3583
3584 // For safety's sake, just ignore it if we don't have type source
3585 // information. This should never happen for non-implicit methods,
3586 // but...
3587 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3588 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3589}
3590
3591/// Check for invalid uses of an abstract type within a class definition.
3592static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3593 CXXRecordDecl *RD) {
3594 for (CXXRecordDecl::decl_iterator
3595 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3596 Decl *D = *I;
3597 if (D->isImplicit()) continue;
3598
3599 // Methods and method templates.
3600 if (isa<CXXMethodDecl>(D)) {
3601 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3602 } else if (isa<FunctionTemplateDecl>(D)) {
3603 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3604 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3605
3606 // Fields and static variables.
3607 } else if (isa<FieldDecl>(D)) {
3608 FieldDecl *FD = cast<FieldDecl>(D);
3609 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3610 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3611 } else if (isa<VarDecl>(D)) {
3612 VarDecl *VD = cast<VarDecl>(D);
3613 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3614 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3615
3616 // Nested classes and class templates.
3617 } else if (isa<CXXRecordDecl>(D)) {
3618 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3619 } else if (isa<ClassTemplateDecl>(D)) {
3620 CheckAbstractClassUsage(Info,
3621 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3622 }
3623 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003624}
3625
Douglas Gregorc99f1552009-12-03 18:33:45 +00003626/// \brief Perform semantic checks on a class definition that has been
3627/// completing, introducing implicitly-declared members, checking for
3628/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003629void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003630 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003631 return;
3632
John McCall02db245d2010-08-18 09:41:07 +00003633 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3634 AbstractUsageInfo Info(*this, Record);
3635 CheckAbstractClassUsage(Info, Record);
3636 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003637
3638 // If this is not an aggregate type and has no user-declared constructor,
3639 // complain about any non-static data members of reference or const scalar
3640 // type, since they will never get initializers.
3641 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00003642 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3643 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003644 bool Complained = false;
3645 for (RecordDecl::field_iterator F = Record->field_begin(),
3646 FEnd = Record->field_end();
3647 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003648 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00003649 continue;
3650
Douglas Gregor454a5b62010-04-15 00:00:53 +00003651 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003652 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003653 if (!Complained) {
3654 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3655 << Record->getTagKind() << Record;
3656 Complained = true;
3657 }
3658
3659 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3660 << F->getType()->isReferenceType()
3661 << F->getDeclName();
3662 }
3663 }
3664 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003665
Anders Carlssone771e762011-01-25 18:08:22 +00003666 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003667 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003668
3669 if (Record->getIdentifier()) {
3670 // C++ [class.mem]p13:
3671 // If T is the name of a class, then each of the following shall have a
3672 // name different from T:
3673 // - every member of every anonymous union that is a member of class T.
3674 //
3675 // C++ [class.mem]p14:
3676 // In addition, if class T has a user-declared constructor (12.1), every
3677 // non-static data member of class T shall have a name different from T.
3678 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003679 R.first != R.second; ++R.first) {
3680 NamedDecl *D = *R.first;
3681 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3682 isa<IndirectFieldDecl>(D)) {
3683 Diag(D->getLocation(), diag::err_member_name_of_class)
3684 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003685 break;
3686 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003687 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003688 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003689
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003690 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003691 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003692 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003693 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003694 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3695 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3696 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003697
3698 // See if a method overloads virtual methods in a base
3699 /// class without overriding any.
3700 if (!Record->isDependentType()) {
3701 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3702 MEnd = Record->method_end();
3703 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003704 if (!(*M)->isStatic())
3705 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003706 }
3707 }
Sebastian Redl08905022011-02-05 19:23:19 +00003708
Richard Smitheb3c10c2011-10-01 02:31:28 +00003709 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3710 // function that is not a constructor declares that member function to be
3711 // const. [...] The class of which that function is a member shall be
3712 // a literal type.
3713 //
3714 // It's fine to diagnose constructors here too: such constructors cannot
3715 // produce a constant expression, so are ill-formed (no diagnostic required).
3716 //
3717 // If the class has virtual bases, any constexpr members will already have
3718 // been diagnosed by the checks performed on the member declaration, so
3719 // suppress this (less useful) diagnostic.
3720 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3721 !Record->isLiteral() && !Record->getNumVBases()) {
3722 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3723 MEnd = Record->method_end();
3724 M != MEnd; ++M) {
Eli Friedmanc8002422012-01-13 02:31:53 +00003725 if (M->isConstexpr() && M->isInstance()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00003726 switch (Record->getTemplateSpecializationKind()) {
3727 case TSK_ImplicitInstantiation:
3728 case TSK_ExplicitInstantiationDeclaration:
3729 case TSK_ExplicitInstantiationDefinition:
3730 // If a template instantiates to a non-literal type, but its members
3731 // instantiate to constexpr functions, the template is technically
3732 // ill-formed, but we allow it for sanity. Such members are treated as
3733 // non-constexpr.
3734 (*M)->setConstexpr(false);
3735 continue;
3736
3737 case TSK_Undeclared:
3738 case TSK_ExplicitSpecialization:
3739 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3740 PDiag(diag::err_constexpr_method_non_literal));
3741 break;
3742 }
3743
3744 // Only produce one error per class.
3745 break;
3746 }
3747 }
3748 }
3749
Sebastian Redl08905022011-02-05 19:23:19 +00003750 // Declare inherited constructors. We do this eagerly here because:
3751 // - The standard requires an eager diagnostic for conflicting inherited
3752 // constructors from different classes.
3753 // - The lazy declaration of the other implicit constructors is so as to not
3754 // waste space and performance on classes that are not meant to be
3755 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3756 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003757 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003758
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003759 if (!Record->isDependentType())
3760 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003761}
3762
3763void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003764 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3765 ME = Record->method_end();
3766 MI != ME; ++MI) {
3767 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3768 switch (getSpecialMember(*MI)) {
3769 case CXXDefaultConstructor:
3770 CheckExplicitlyDefaultedDefaultConstructor(
3771 cast<CXXConstructorDecl>(*MI));
3772 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003773
Alexis Huntf91729462011-05-12 22:46:25 +00003774 case CXXDestructor:
3775 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3776 break;
3777
3778 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003779 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3780 break;
3781
Alexis Huntf91729462011-05-12 22:46:25 +00003782 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003783 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003784 break;
3785
Alexis Hunt119c10e2011-05-25 23:16:36 +00003786 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003787 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003788 break;
3789
Sebastian Redl22653ba2011-08-30 19:58:05 +00003790 case CXXMoveAssignment:
3791 CheckExplicitlyDefaultedMoveAssignment(*MI);
3792 break;
3793
3794 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003795 llvm_unreachable("non-special member explicitly defaulted!");
3796 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003797 }
3798 }
3799
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003800}
3801
3802void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3803 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3804
3805 // Whether this was the first-declared instance of the constructor.
3806 // This affects whether we implicitly add an exception spec (and, eventually,
3807 // constexpr). It is also ill-formed to explicitly default a constructor such
3808 // that it would be deleted. (C++0x [decl.fct.def.default])
3809 bool First = CD == CD->getCanonicalDecl();
3810
Alexis Hunt913820d2011-05-13 06:10:58 +00003811 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003812 if (CD->getNumParams() != 0) {
3813 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3814 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003815 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003816 }
3817
3818 ImplicitExceptionSpecification Spec
3819 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3820 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003821 if (EPI.ExceptionSpecType == EST_Delayed) {
3822 // Exception specification depends on some deferred part of the class. We'll
3823 // try again when the class's definition has been fully processed.
3824 return;
3825 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003826 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3827 *ExceptionType = Context.getFunctionType(
3828 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3829
Richard Smithcc36f692011-12-22 02:22:31 +00003830 // C++11 [dcl.fct.def.default]p2:
3831 // An explicitly-defaulted function may be declared constexpr only if it
3832 // would have been implicitly declared as constexpr,
3833 if (CD->isConstexpr()) {
3834 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3835 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3836 << CXXDefaultConstructor;
3837 HadError = true;
3838 }
3839 }
3840 // and may have an explicit exception-specification only if it is compatible
3841 // with the exception-specification on the implicit declaration.
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003842 if (CtorType->hasExceptionSpec()) {
3843 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003844 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003845 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003846 PDiag(),
3847 ExceptionType, SourceLocation(),
3848 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003849 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003850 }
Richard Smithcc36f692011-12-22 02:22:31 +00003851 }
3852
3853 // If a function is explicitly defaulted on its first declaration,
3854 if (First) {
3855 // -- it is implicitly considered to be constexpr if the implicit
3856 // definition would be,
3857 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3858
3859 // -- it is implicitly considered to have the same
3860 // exception-specification as if it had been implicitly declared
3861 //
3862 // FIXME: a compatible, but different, explicit exception specification
3863 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003864 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003865 }
Alexis Huntb3153022011-05-12 03:51:48 +00003866
Alexis Hunt913820d2011-05-13 06:10:58 +00003867 if (HadError) {
3868 CD->setInvalidDecl();
3869 return;
3870 }
3871
Alexis Huntd6da8762011-10-10 06:18:57 +00003872 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003873 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003874 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003875 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003876 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003877 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003878 CD->setInvalidDecl();
3879 }
3880 }
3881}
3882
3883void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3884 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3885
3886 // Whether this was the first-declared instance of the constructor.
3887 bool First = CD == CD->getCanonicalDecl();
3888
3889 bool HadError = false;
3890 if (CD->getNumParams() != 1) {
3891 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3892 << CD->getSourceRange();
3893 HadError = true;
3894 }
3895
3896 ImplicitExceptionSpecification Spec(Context);
3897 bool Const;
3898 llvm::tie(Spec, Const) =
3899 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3900
3901 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3902 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3903 *ExceptionType = Context.getFunctionType(
3904 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3905
3906 // Check for parameter type matching.
3907 // This is a copy ctor so we know it's a cv-qualified reference to T.
3908 QualType ArgType = CtorType->getArgType(0);
3909 if (ArgType->getPointeeType().isVolatileQualified()) {
3910 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3911 HadError = true;
3912 }
3913 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3914 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3915 HadError = true;
3916 }
3917
Richard Smithcc36f692011-12-22 02:22:31 +00003918 // C++11 [dcl.fct.def.default]p2:
3919 // An explicitly-defaulted function may be declared constexpr only if it
3920 // would have been implicitly declared as constexpr,
3921 if (CD->isConstexpr()) {
3922 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3923 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3924 << CXXCopyConstructor;
3925 HadError = true;
3926 }
3927 }
3928 // and may have an explicit exception-specification only if it is compatible
3929 // with the exception-specification on the implicit declaration.
Alexis Hunt913820d2011-05-13 06:10:58 +00003930 if (CtorType->hasExceptionSpec()) {
3931 if (CheckEquivalentExceptionSpec(
3932 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003933 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003934 PDiag(),
3935 ExceptionType, SourceLocation(),
3936 CtorType, CD->getLocation())) {
3937 HadError = true;
3938 }
Richard Smithcc36f692011-12-22 02:22:31 +00003939 }
3940
3941 // If a function is explicitly defaulted on its first declaration,
3942 if (First) {
3943 // -- it is implicitly considered to be constexpr if the implicit
3944 // definition would be,
3945 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3946
3947 // -- it is implicitly considered to have the same
3948 // exception-specification as if it had been implicitly declared, and
3949 //
3950 // FIXME: a compatible, but different, explicit exception specification
3951 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003952 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00003953
3954 // -- [...] it shall have the same parameter type as if it had been
3955 // implicitly declared.
Alexis Hunt913820d2011-05-13 06:10:58 +00003956 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3957 }
3958
3959 if (HadError) {
3960 CD->setInvalidDecl();
3961 return;
3962 }
3963
Alexis Hunt1bc6f712011-10-11 04:55:36 +00003964 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003965 if (First) {
3966 CD->setDeletedAsWritten();
3967 } else {
3968 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003969 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003970 CD->setInvalidDecl();
3971 }
Alexis Huntb3153022011-05-12 03:51:48 +00003972 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003973}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003974
Alexis Huntc9a55732011-05-14 05:23:28 +00003975void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3976 assert(MD->isExplicitlyDefaulted());
3977
3978 // Whether this was the first-declared instance of the operator
3979 bool First = MD == MD->getCanonicalDecl();
3980
3981 bool HadError = false;
3982 if (MD->getNumParams() != 1) {
3983 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3984 << MD->getSourceRange();
3985 HadError = true;
3986 }
3987
3988 QualType ReturnType =
3989 MD->getType()->getAs<FunctionType>()->getResultType();
3990 if (!ReturnType->isLValueReferenceType() ||
3991 !Context.hasSameType(
3992 Context.getCanonicalType(ReturnType->getPointeeType()),
3993 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3994 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3995 HadError = true;
3996 }
3997
3998 ImplicitExceptionSpecification Spec(Context);
3999 bool Const;
4000 llvm::tie(Spec, Const) =
4001 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4002
4003 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4004 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4005 *ExceptionType = Context.getFunctionType(
4006 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4007
Alexis Huntc9a55732011-05-14 05:23:28 +00004008 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004009 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00004010 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004011 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00004012 } else {
4013 if (ArgType->getPointeeType().isVolatileQualified()) {
4014 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4015 HadError = true;
4016 }
4017 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4018 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4019 HadError = true;
4020 }
Alexis Huntc9a55732011-05-14 05:23:28 +00004021 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004022
Alexis Huntc9a55732011-05-14 05:23:28 +00004023 if (OperType->getTypeQuals()) {
4024 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4025 HadError = true;
4026 }
4027
4028 if (OperType->hasExceptionSpec()) {
4029 if (CheckEquivalentExceptionSpec(
4030 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004031 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00004032 PDiag(),
4033 ExceptionType, SourceLocation(),
4034 OperType, MD->getLocation())) {
4035 HadError = true;
4036 }
Richard Smithcc36f692011-12-22 02:22:31 +00004037 }
4038 if (First) {
Alexis Huntc9a55732011-05-14 05:23:28 +00004039 // We set the declaration to have the computed exception spec here.
4040 // We duplicate the one parameter type.
4041 EPI.RefQualifier = OperType->getRefQualifier();
4042 EPI.ExtInfo = OperType->getExtInfo();
4043 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4044 }
4045
4046 if (HadError) {
4047 MD->setInvalidDecl();
4048 return;
4049 }
4050
4051 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4052 if (First) {
4053 MD->setDeletedAsWritten();
4054 } else {
4055 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004056 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00004057 MD->setInvalidDecl();
4058 }
4059 }
4060}
4061
Sebastian Redl22653ba2011-08-30 19:58:05 +00004062void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4063 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4064
4065 // Whether this was the first-declared instance of the constructor.
4066 bool First = CD == CD->getCanonicalDecl();
4067
4068 bool HadError = false;
4069 if (CD->getNumParams() != 1) {
4070 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4071 << CD->getSourceRange();
4072 HadError = true;
4073 }
4074
4075 ImplicitExceptionSpecification Spec(
4076 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4077
4078 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4079 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4080 *ExceptionType = Context.getFunctionType(
4081 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4082
4083 // Check for parameter type matching.
4084 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4085 QualType ArgType = CtorType->getArgType(0);
4086 if (ArgType->getPointeeType().isVolatileQualified()) {
4087 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4088 HadError = true;
4089 }
4090 if (ArgType->getPointeeType().isConstQualified()) {
4091 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4092 HadError = true;
4093 }
4094
Richard Smithcc36f692011-12-22 02:22:31 +00004095 // C++11 [dcl.fct.def.default]p2:
4096 // An explicitly-defaulted function may be declared constexpr only if it
4097 // would have been implicitly declared as constexpr,
4098 if (CD->isConstexpr()) {
4099 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4100 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4101 << CXXMoveConstructor;
4102 HadError = true;
4103 }
4104 }
4105 // and may have an explicit exception-specification only if it is compatible
4106 // with the exception-specification on the implicit declaration.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004107 if (CtorType->hasExceptionSpec()) {
4108 if (CheckEquivalentExceptionSpec(
4109 PDiag(diag::err_incorrect_defaulted_exception_spec)
4110 << CXXMoveConstructor,
4111 PDiag(),
4112 ExceptionType, SourceLocation(),
4113 CtorType, CD->getLocation())) {
4114 HadError = true;
4115 }
Richard Smithcc36f692011-12-22 02:22:31 +00004116 }
4117
4118 // If a function is explicitly defaulted on its first declaration,
4119 if (First) {
4120 // -- it is implicitly considered to be constexpr if the implicit
4121 // definition would be,
4122 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4123
4124 // -- it is implicitly considered to have the same
4125 // exception-specification as if it had been implicitly declared, and
4126 //
4127 // FIXME: a compatible, but different, explicit exception specification
4128 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004129 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00004130
4131 // -- [...] it shall have the same parameter type as if it had been
4132 // implicitly declared.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004133 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4134 }
4135
4136 if (HadError) {
4137 CD->setInvalidDecl();
4138 return;
4139 }
4140
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004141 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004142 if (First) {
4143 CD->setDeletedAsWritten();
4144 } else {
4145 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4146 << CXXMoveConstructor;
4147 CD->setInvalidDecl();
4148 }
4149 }
4150}
4151
4152void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4153 assert(MD->isExplicitlyDefaulted());
4154
4155 // Whether this was the first-declared instance of the operator
4156 bool First = MD == MD->getCanonicalDecl();
4157
4158 bool HadError = false;
4159 if (MD->getNumParams() != 1) {
4160 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4161 << MD->getSourceRange();
4162 HadError = true;
4163 }
4164
4165 QualType ReturnType =
4166 MD->getType()->getAs<FunctionType>()->getResultType();
4167 if (!ReturnType->isLValueReferenceType() ||
4168 !Context.hasSameType(
4169 Context.getCanonicalType(ReturnType->getPointeeType()),
4170 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4171 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4172 HadError = true;
4173 }
4174
4175 ImplicitExceptionSpecification Spec(
4176 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4177
4178 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4179 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4180 *ExceptionType = Context.getFunctionType(
4181 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4182
4183 QualType ArgType = OperType->getArgType(0);
4184 if (!ArgType->isRValueReferenceType()) {
4185 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4186 HadError = true;
4187 } else {
4188 if (ArgType->getPointeeType().isVolatileQualified()) {
4189 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4190 HadError = true;
4191 }
4192 if (ArgType->getPointeeType().isConstQualified()) {
4193 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4194 HadError = true;
4195 }
4196 }
4197
4198 if (OperType->getTypeQuals()) {
4199 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4200 HadError = true;
4201 }
4202
4203 if (OperType->hasExceptionSpec()) {
4204 if (CheckEquivalentExceptionSpec(
4205 PDiag(diag::err_incorrect_defaulted_exception_spec)
4206 << CXXMoveAssignment,
4207 PDiag(),
4208 ExceptionType, SourceLocation(),
4209 OperType, MD->getLocation())) {
4210 HadError = true;
4211 }
Richard Smithcc36f692011-12-22 02:22:31 +00004212 }
4213 if (First) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004214 // We set the declaration to have the computed exception spec here.
4215 // We duplicate the one parameter type.
4216 EPI.RefQualifier = OperType->getRefQualifier();
4217 EPI.ExtInfo = OperType->getExtInfo();
4218 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4219 }
4220
4221 if (HadError) {
4222 MD->setInvalidDecl();
4223 return;
4224 }
4225
4226 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4227 if (First) {
4228 MD->setDeletedAsWritten();
4229 } else {
4230 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4231 << CXXMoveAssignment;
4232 MD->setInvalidDecl();
4233 }
4234 }
4235}
4236
Alexis Huntf91729462011-05-12 22:46:25 +00004237void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4238 assert(DD->isExplicitlyDefaulted());
4239
4240 // Whether this was the first-declared instance of the destructor.
4241 bool First = DD == DD->getCanonicalDecl();
4242
4243 ImplicitExceptionSpecification Spec
4244 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4245 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4246 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4247 *ExceptionType = Context.getFunctionType(
4248 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4249
4250 if (DtorType->hasExceptionSpec()) {
4251 if (CheckEquivalentExceptionSpec(
4252 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004253 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00004254 PDiag(),
4255 ExceptionType, SourceLocation(),
4256 DtorType, DD->getLocation())) {
4257 DD->setInvalidDecl();
4258 return;
4259 }
Richard Smithcc36f692011-12-22 02:22:31 +00004260 }
4261 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004262 // We set the declaration to have the computed exception spec here.
4263 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00004264 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00004265 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4266 }
4267
4268 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00004269 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004270 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00004271 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00004272 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004273 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00004274 DD->setInvalidDecl();
4275 }
Alexis Huntf91729462011-05-12 22:46:25 +00004276 }
Alexis Huntf91729462011-05-12 22:46:25 +00004277}
4278
Alexis Huntd6da8762011-10-10 06:18:57 +00004279/// This function implements the following C++0x paragraphs:
4280/// - [class.ctor]/5
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004281/// - [class.copy]/11
Alexis Huntd6da8762011-10-10 06:18:57 +00004282bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4283 assert(!MD->isInvalidDecl());
4284 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00004285 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004286 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004287 return false;
4288
Alexis Huntd6da8762011-10-10 06:18:57 +00004289 bool IsUnion = RD->isUnion();
4290 bool IsConstructor = false;
4291 bool IsAssignment = false;
4292 bool IsMove = false;
4293
4294 bool ConstArg = false;
4295
4296 switch (CSM) {
4297 case CXXDefaultConstructor:
4298 IsConstructor = true;
4299 break;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004300 case CXXCopyConstructor:
4301 IsConstructor = true;
4302 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4303 break;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004304 case CXXMoveConstructor:
4305 IsConstructor = true;
4306 IsMove = true;
4307 break;
Alexis Huntd6da8762011-10-10 06:18:57 +00004308 default:
4309 llvm_unreachable("function only currently implemented for default ctors");
4310 }
4311
4312 SourceLocation Loc = MD->getLocation();
Alexis Hunte77a28f2011-05-18 03:41:58 +00004313
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004314 // Do access control from the special member function
Alexis Huntd6da8762011-10-10 06:18:57 +00004315 ContextRAII MethodContext(*this, MD);
Alexis Huntea6f0322011-05-11 22:34:38 +00004316
Alexis Huntea6f0322011-05-11 22:34:38 +00004317 bool AllConst = true;
4318
Alexis Huntea6f0322011-05-11 22:34:38 +00004319 // We do this because we should never actually use an anonymous
4320 // union's constructor.
Alexis Huntd6da8762011-10-10 06:18:57 +00004321 if (IsUnion && RD->isAnonymousStructOrUnion())
Alexis Huntea6f0322011-05-11 22:34:38 +00004322 return false;
4323
4324 // FIXME: We should put some diagnostic logic right into this function.
4325
Alexis Huntea6f0322011-05-11 22:34:38 +00004326 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4327 BE = RD->bases_end();
4328 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00004329 // We'll handle this one later
4330 if (BI->isVirtual())
4331 continue;
4332
Alexis Huntea6f0322011-05-11 22:34:38 +00004333 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4334 assert(BaseDecl && "base isn't a CXXRecordDecl");
4335
Alexis Huntd6da8762011-10-10 06:18:57 +00004336 // Unless we have an assignment operator, the base's destructor must
4337 // be accessible and not deleted.
4338 if (!IsAssignment) {
4339 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4340 if (BaseDtor->isDeleted())
4341 return true;
4342 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4343 AR_accessible)
4344 return true;
4345 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004346
Alexis Huntd6da8762011-10-10 06:18:57 +00004347 // Finding the corresponding member in the base should lead to a
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004348 // unique, accessible, non-deleted function. If we are doing
4349 // a destructor, we have already checked this case.
Alexis Huntd6da8762011-10-10 06:18:57 +00004350 if (CSM != CXXDestructor) {
4351 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004352 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004353 false);
4354 if (!SMOR->hasSuccess())
4355 return true;
4356 CXXMethodDecl *BaseMember = SMOR->getMethod();
4357 if (IsConstructor) {
4358 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4359 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4360 PDiag()) != AR_accessible)
4361 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004362
4363 // For a move operation, the corresponding operation must actually
4364 // be a move operation (and not a copy selected by overload
4365 // resolution) unless we are working on a trivially copyable class.
4366 if (IsMove && !BaseCtor->isMoveConstructor() &&
4367 !BaseDecl->isTriviallyCopyable())
4368 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004369 }
4370 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004371 }
4372
4373 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4374 BE = RD->vbases_end();
4375 BI != BE; ++BI) {
4376 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4377 assert(BaseDecl && "base isn't a CXXRecordDecl");
4378
Alexis Huntd6da8762011-10-10 06:18:57 +00004379 // Unless we have an assignment operator, the base's destructor must
4380 // be accessible and not deleted.
4381 if (!IsAssignment) {
4382 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4383 if (BaseDtor->isDeleted())
4384 return true;
4385 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4386 AR_accessible)
4387 return true;
4388 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004389
Alexis Huntd6da8762011-10-10 06:18:57 +00004390 // Finding the corresponding member in the base should lead to a
4391 // unique, accessible, non-deleted function.
4392 if (CSM != CXXDestructor) {
4393 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004394 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004395 false);
4396 if (!SMOR->hasSuccess())
4397 return true;
4398 CXXMethodDecl *BaseMember = SMOR->getMethod();
4399 if (IsConstructor) {
4400 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4401 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4402 PDiag()) != AR_accessible)
4403 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004404
4405 // For a move operation, the corresponding operation must actually
4406 // be a move operation (and not a copy selected by overload
4407 // resolution) unless we are working on a trivially copyable class.
4408 if (IsMove && !BaseCtor->isMoveConstructor() &&
4409 !BaseDecl->isTriviallyCopyable())
4410 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004411 }
4412 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004413 }
4414
4415 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4416 FE = RD->field_end();
4417 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004418 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004419 continue;
4420
Alexis Huntea6f0322011-05-11 22:34:38 +00004421 QualType FieldType = Context.getBaseElementType(FI->getType());
4422 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00004423
Alexis Huntd6da8762011-10-10 06:18:57 +00004424 // For a default constructor, all references must be initialized in-class
4425 // and, if a union, it must have a non-const member.
4426 if (CSM == CXXDefaultConstructor) {
4427 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4428 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004429
Alexis Huntd6da8762011-10-10 06:18:57 +00004430 if (IsUnion && !FieldType.isConstQualified())
4431 AllConst = false;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004432 // For a copy constructor, data members must not be of rvalue reference
4433 // type.
4434 } else if (CSM == CXXCopyConstructor) {
4435 if (FieldType->isRValueReferenceType())
4436 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004437 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004438
4439 if (FieldRecord) {
Alexis Huntd6da8762011-10-10 06:18:57 +00004440 // For a default constructor, a const member must have a user-provided
4441 // default constructor or else be explicitly initialized.
4442 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00004443 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004444 !FieldRecord->hasUserProvidedDefaultConstructor())
4445 return true;
4446
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004447 // Some additional restrictions exist on the variant members.
4448 if (!IsUnion && FieldRecord->isUnion() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004449 FieldRecord->isAnonymousStructOrUnion()) {
4450 // We're okay to reuse AllConst here since we only care about the
4451 // value otherwise if we're in a union.
4452 AllConst = true;
4453
4454 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4455 UE = FieldRecord->field_end();
4456 UI != UE; ++UI) {
4457 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4458 CXXRecordDecl *UnionFieldRecord =
4459 UnionFieldType->getAsCXXRecordDecl();
4460
4461 if (!UnionFieldType.isConstQualified())
4462 AllConst = false;
4463
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004464 if (UnionFieldRecord) {
4465 // FIXME: Checking for accessibility and validity of this
4466 // destructor is technically going beyond the
4467 // standard, but this is believed to be a defect.
4468 if (!IsAssignment) {
4469 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4470 if (FieldDtor->isDeleted())
4471 return true;
4472 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4473 AR_accessible)
4474 return true;
4475 if (!FieldDtor->isTrivial())
4476 return true;
4477 }
4478
4479 if (CSM != CXXDestructor) {
4480 SpecialMemberOverloadResult *SMOR =
4481 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004482 false, false, false);
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004483 // FIXME: Checking for accessibility and validity of this
4484 // corresponding member is technically going beyond the
4485 // standard, but this is believed to be a defect.
4486 if (!SMOR->hasSuccess())
4487 return true;
4488
4489 CXXMethodDecl *FieldMember = SMOR->getMethod();
4490 // A member of a union must have a trivial corresponding
4491 // constructor.
4492 if (!FieldMember->isTrivial())
4493 return true;
4494
4495 if (IsConstructor) {
4496 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4497 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4498 PDiag()) != AR_accessible)
4499 return true;
4500 }
4501 }
4502 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004503 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00004504
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004505 // At least one member in each anonymous union must be non-const
4506 if (CSM == CXXDefaultConstructor && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004507 return true;
4508
4509 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00004510 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00004511 continue;
4512 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00004513
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004514 // Unless we're doing assignment, the field's destructor must be
4515 // accessible and not deleted.
4516 if (!IsAssignment) {
4517 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4518 if (FieldDtor->isDeleted())
4519 return true;
4520 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4521 AR_accessible)
4522 return true;
4523 }
4524
Alexis Huntd6da8762011-10-10 06:18:57 +00004525 // Check that the corresponding member of the field is accessible,
4526 // unique, and non-deleted. We don't do this if it has an explicit
4527 // initialization when default-constructing.
4528 if (CSM != CXXDestructor &&
4529 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4530 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004531 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004532 false);
4533 if (!SMOR->hasSuccess())
Richard Smith938f40b2011-06-11 17:19:42 +00004534 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004535
4536 CXXMethodDecl *FieldMember = SMOR->getMethod();
4537 if (IsConstructor) {
4538 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4539 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4540 PDiag()) != AR_accessible)
4541 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004542
4543 // For a move operation, the corresponding operation must actually
4544 // be a move operation (and not a copy selected by overload
4545 // resolution) unless we are working on a trivially copyable class.
4546 if (IsMove && !FieldCtor->isMoveConstructor() &&
4547 !FieldRecord->isTriviallyCopyable())
4548 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004549 }
4550
4551 // We need the corresponding member of a union to be trivial so that
4552 // we can safely copy them all simultaneously.
4553 // FIXME: Note that performing the check here (where we rely on the lack
4554 // of an in-class initializer) is technically ill-formed. However, this
4555 // seems most obviously to be a bug in the standard.
4556 if (IsUnion && !FieldMember->isTrivial())
Richard Smith938f40b2011-06-11 17:19:42 +00004557 return true;
4558 }
Alexis Huntd6da8762011-10-10 06:18:57 +00004559 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4560 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4561 // We can't initialize a const member of non-class type to any value.
Alexis Hunta671bca2011-05-20 21:43:47 +00004562 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004563 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004564 }
4565
Alexis Huntd6da8762011-10-10 06:18:57 +00004566 // We can't have all const members in a union when default-constructing,
4567 // or else they're all nonsensical garbage values that can't be changed.
4568 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004569 return true;
4570
4571 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004572}
4573
Alexis Huntb2f27802011-05-14 05:23:24 +00004574bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4575 CXXRecordDecl *RD = MD->getParent();
4576 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004577 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004578 return false;
4579
Alexis Hunte77a28f2011-05-18 03:41:58 +00004580 SourceLocation Loc = MD->getLocation();
4581
Alexis Huntb2f27802011-05-14 05:23:24 +00004582 // Do access control from the constructor
4583 ContextRAII MethodContext(*this, MD);
4584
4585 bool Union = RD->isUnion();
4586
Alexis Hunt491ec602011-06-21 23:42:56 +00004587 unsigned ArgQuals =
4588 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4589 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004590
4591 // We do this because we should never actually use an anonymous
4592 // union's constructor.
4593 if (Union && RD->isAnonymousStructOrUnion())
4594 return false;
4595
Alexis Huntb2f27802011-05-14 05:23:24 +00004596 // FIXME: We should put some diagnostic logic right into this function.
4597
Sebastian Redl22653ba2011-08-30 19:58:05 +00004598 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004599 // A defaulted [copy] assignment operator for class X is defined as deleted
4600 // if X has:
4601
4602 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4603 BE = RD->bases_end();
4604 BI != BE; ++BI) {
4605 // We'll handle this one later
4606 if (BI->isVirtual())
4607 continue;
4608
4609 QualType BaseType = BI->getType();
4610 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4611 assert(BaseDecl && "base isn't a CXXRecordDecl");
4612
4613 // -- a [direct base class] B that cannot be [copied] because overload
4614 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004615 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004616 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004617 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4618 0);
4619 if (!CopyOper || CopyOper->isDeleted())
4620 return true;
4621 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004622 return true;
4623 }
4624
4625 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4626 BE = RD->vbases_end();
4627 BI != BE; ++BI) {
4628 QualType BaseType = BI->getType();
4629 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4630 assert(BaseDecl && "base isn't a CXXRecordDecl");
4631
Alexis Huntb2f27802011-05-14 05:23:24 +00004632 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004633 // resolution, as applied to B's [copy] assignment operator, results in
4634 // an ambiguity or a function that is deleted or inaccessible from the
4635 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004636 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4637 0);
4638 if (!CopyOper || CopyOper->isDeleted())
4639 return true;
4640 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004641 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004642 }
4643
4644 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4645 FE = RD->field_end();
4646 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004647 if (FI->isUnnamedBitfield())
4648 continue;
4649
Alexis Huntb2f27802011-05-14 05:23:24 +00004650 QualType FieldType = Context.getBaseElementType(FI->getType());
4651
4652 // -- a non-static data member of reference type
4653 if (FieldType->isReferenceType())
4654 return true;
4655
4656 // -- a non-static data member of const non-class type (or array thereof)
4657 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4658 return true;
4659
4660 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4661
4662 if (FieldRecord) {
4663 // This is an anonymous union
4664 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4665 // Anonymous unions inside unions do not variant members create
4666 if (!Union) {
4667 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4668 UE = FieldRecord->field_end();
4669 UI != UE; ++UI) {
4670 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4671 CXXRecordDecl *UnionFieldRecord =
4672 UnionFieldType->getAsCXXRecordDecl();
4673
4674 // -- a variant member with a non-trivial [copy] assignment operator
4675 // and X is a union-like class
4676 if (UnionFieldRecord &&
4677 !UnionFieldRecord->hasTrivialCopyAssignment())
4678 return true;
4679 }
4680 }
4681
4682 // Don't try to initalize an anonymous union
4683 continue;
4684 // -- a variant member with a non-trivial [copy] assignment operator
4685 // and X is a union-like class
4686 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4687 return true;
4688 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004689
Alexis Hunt491ec602011-06-21 23:42:56 +00004690 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4691 false, 0);
4692 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004693 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004694 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004695 return true;
4696 }
4697 }
4698
4699 return false;
4700}
4701
Sebastian Redl22653ba2011-08-30 19:58:05 +00004702bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4703 CXXRecordDecl *RD = MD->getParent();
4704 assert(!RD->isDependentType() && "do deletion after instantiation");
4705 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4706 return false;
4707
4708 SourceLocation Loc = MD->getLocation();
4709
4710 // Do access control from the constructor
4711 ContextRAII MethodContext(*this, MD);
4712
4713 bool Union = RD->isUnion();
4714
4715 // We do this because we should never actually use an anonymous
4716 // union's constructor.
4717 if (Union && RD->isAnonymousStructOrUnion())
4718 return false;
4719
4720 // C++0x [class.copy]/20
4721 // A defaulted [move] assignment operator for class X is defined as deleted
4722 // if X has:
4723
4724 // -- for the move constructor, [...] any direct or indirect virtual base
4725 // class.
4726 if (RD->getNumVBases() != 0)
4727 return true;
4728
4729 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4730 BE = RD->bases_end();
4731 BI != BE; ++BI) {
4732
4733 QualType BaseType = BI->getType();
4734 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4735 assert(BaseDecl && "base isn't a CXXRecordDecl");
4736
4737 // -- a [direct base class] B that cannot be [moved] because overload
4738 // resolution, as applied to B's [move] assignment operator, results in
4739 // an ambiguity or a function that is deleted or inaccessible from the
4740 // assignment operator
4741 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4742 if (!MoveOper || MoveOper->isDeleted())
4743 return true;
4744 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4745 return true;
4746
4747 // -- for the move assignment operator, a [direct base class] with a type
4748 // that does not have a move assignment operator and is not trivially
4749 // copyable.
4750 if (!MoveOper->isMoveAssignmentOperator() &&
4751 !BaseDecl->isTriviallyCopyable())
4752 return true;
4753 }
4754
4755 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4756 FE = RD->field_end();
4757 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004758 if (FI->isUnnamedBitfield())
4759 continue;
4760
Sebastian Redl22653ba2011-08-30 19:58:05 +00004761 QualType FieldType = Context.getBaseElementType(FI->getType());
4762
4763 // -- a non-static data member of reference type
4764 if (FieldType->isReferenceType())
4765 return true;
4766
4767 // -- a non-static data member of const non-class type (or array thereof)
4768 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4769 return true;
4770
4771 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4772
4773 if (FieldRecord) {
4774 // This is an anonymous union
4775 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4776 // Anonymous unions inside unions do not variant members create
4777 if (!Union) {
4778 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4779 UE = FieldRecord->field_end();
4780 UI != UE; ++UI) {
4781 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4782 CXXRecordDecl *UnionFieldRecord =
4783 UnionFieldType->getAsCXXRecordDecl();
4784
4785 // -- a variant member with a non-trivial [move] assignment operator
4786 // and X is a union-like class
4787 if (UnionFieldRecord &&
4788 !UnionFieldRecord->hasTrivialMoveAssignment())
4789 return true;
4790 }
4791 }
4792
4793 // Don't try to initalize an anonymous union
4794 continue;
4795 // -- a variant member with a non-trivial [move] assignment operator
4796 // and X is a union-like class
4797 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4798 return true;
4799 }
4800
4801 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4802 if (!MoveOper || MoveOper->isDeleted())
4803 return true;
4804 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4805 return true;
4806
4807 // -- for the move assignment operator, a [non-static data member] with a
4808 // type that does not have a move assignment operator and is not
4809 // trivially copyable.
4810 if (!MoveOper->isMoveAssignmentOperator() &&
4811 !FieldRecord->isTriviallyCopyable())
4812 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004813 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004814 }
4815
4816 return false;
4817}
4818
Alexis Huntf91729462011-05-12 22:46:25 +00004819bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4820 CXXRecordDecl *RD = DD->getParent();
4821 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004822 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004823 return false;
4824
Alexis Hunte77a28f2011-05-18 03:41:58 +00004825 SourceLocation Loc = DD->getLocation();
4826
Alexis Huntf91729462011-05-12 22:46:25 +00004827 // Do access control from the destructor
4828 ContextRAII CtorContext(*this, DD);
4829
4830 bool Union = RD->isUnion();
4831
Alexis Hunt913820d2011-05-13 06:10:58 +00004832 // We do this because we should never actually use an anonymous
4833 // union's destructor.
4834 if (Union && RD->isAnonymousStructOrUnion())
4835 return false;
4836
Alexis Huntf91729462011-05-12 22:46:25 +00004837 // C++0x [class.dtor]p5
4838 // A defaulted destructor for a class X is defined as deleted if:
4839 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4840 BE = RD->bases_end();
4841 BI != BE; ++BI) {
4842 // We'll handle this one later
4843 if (BI->isVirtual())
4844 continue;
4845
4846 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4847 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4848 assert(BaseDtor && "base has no destructor");
4849
4850 // -- any direct or virtual base class has a deleted destructor or
4851 // a destructor that is inaccessible from the defaulted destructor
4852 if (BaseDtor->isDeleted())
4853 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004854 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004855 AR_accessible)
4856 return true;
4857 }
4858
4859 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4860 BE = RD->vbases_end();
4861 BI != BE; ++BI) {
4862 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4863 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4864 assert(BaseDtor && "base has no destructor");
4865
4866 // -- any direct or virtual base class has a deleted destructor or
4867 // a destructor that is inaccessible from the defaulted destructor
4868 if (BaseDtor->isDeleted())
4869 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004870 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004871 AR_accessible)
4872 return true;
4873 }
4874
4875 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4876 FE = RD->field_end();
4877 FI != FE; ++FI) {
4878 QualType FieldType = Context.getBaseElementType(FI->getType());
4879 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4880 if (FieldRecord) {
4881 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4882 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4883 UE = FieldRecord->field_end();
4884 UI != UE; ++UI) {
4885 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4886 CXXRecordDecl *UnionFieldRecord =
4887 UnionFieldType->getAsCXXRecordDecl();
4888
4889 // -- X is a union-like class that has a variant member with a non-
4890 // trivial destructor.
4891 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4892 return true;
4893 }
4894 // Technically we are supposed to do this next check unconditionally.
4895 // But that makes absolutely no sense.
4896 } else {
4897 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4898
4899 // -- any of the non-static data members has class type M (or array
4900 // thereof) and M has a deleted destructor or a destructor that is
4901 // inaccessible from the defaulted destructor
4902 if (FieldDtor->isDeleted())
4903 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004904 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004905 AR_accessible)
4906 return true;
4907
4908 // -- X is a union-like class that has a variant member with a non-
4909 // trivial destructor.
4910 if (Union && !FieldDtor->isTrivial())
4911 return true;
4912 }
4913 }
4914 }
4915
4916 if (DD->isVirtual()) {
4917 FunctionDecl *OperatorDelete = 0;
4918 DeclarationName Name =
4919 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004920 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004921 false))
4922 return true;
4923 }
4924
4925
4926 return false;
4927}
4928
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004929/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004930namespace {
4931 struct FindHiddenVirtualMethodData {
4932 Sema *S;
4933 CXXMethodDecl *Method;
4934 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004935 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004936 };
4937}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004938
4939/// \brief Member lookup function that determines whether a given C++
4940/// method overloads virtual methods in a base class without overriding any,
4941/// to be used with CXXRecordDecl::lookupInBases().
4942static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4943 CXXBasePath &Path,
4944 void *UserData) {
4945 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4946
4947 FindHiddenVirtualMethodData &Data
4948 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4949
4950 DeclarationName Name = Data.Method->getDeclName();
4951 assert(Name.getNameKind() == DeclarationName::Identifier);
4952
4953 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004954 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004955 for (Path.Decls = BaseRecord->lookup(Name);
4956 Path.Decls.first != Path.Decls.second;
4957 ++Path.Decls.first) {
4958 NamedDecl *D = *Path.Decls.first;
4959 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004960 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004961 foundSameNameMethod = true;
4962 // Interested only in hidden virtual methods.
4963 if (!MD->isVirtual())
4964 continue;
4965 // If the method we are checking overrides a method from its base
4966 // don't warn about the other overloaded methods.
4967 if (!Data.S->IsOverload(Data.Method, MD, false))
4968 return true;
4969 // Collect the overload only if its hidden.
4970 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4971 overloadedMethods.push_back(MD);
4972 }
4973 }
4974
4975 if (foundSameNameMethod)
4976 Data.OverloadedMethods.append(overloadedMethods.begin(),
4977 overloadedMethods.end());
4978 return foundSameNameMethod;
4979}
4980
4981/// \brief See if a method overloads virtual methods in a base class without
4982/// overriding any.
4983void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4984 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00004985 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004986 return;
4987 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4988 return;
4989
4990 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4991 /*bool RecordPaths=*/false,
4992 /*bool DetectVirtual=*/false);
4993 FindHiddenVirtualMethodData Data;
4994 Data.Method = MD;
4995 Data.S = this;
4996
4997 // Keep the base methods that were overriden or introduced in the subclass
4998 // by 'using' in a set. A base method not in this set is hidden.
4999 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5000 res.first != res.second; ++res.first) {
5001 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5002 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5003 E = MD->end_overridden_methods();
5004 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005005 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005006 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005008 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005009 }
5010
5011 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5012 !Data.OverloadedMethods.empty()) {
5013 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5014 << MD << (Data.OverloadedMethods.size() > 1);
5015
5016 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5017 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5018 Diag(overloadedMD->getLocation(),
5019 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5020 }
5021 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005022}
5023
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005024void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005025 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005026 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005027 SourceLocation RBrac,
5028 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005029 if (!TagDecl)
5030 return;
Mike Stump11289f42009-09-09 15:08:12 +00005031
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005032 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005033
David Blaikie751c5582011-09-22 02:58:26 +00005034 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005035 // strict aliasing violation!
5036 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005037 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005038
Douglas Gregor0be31a22010-07-02 17:43:08 +00005039 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005040 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005041}
5042
Douglas Gregor05379422008-11-03 17:51:48 +00005043/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5044/// special functions, such as the default constructor, copy
5045/// constructor, or destructor, to the given C++ class (C++
5046/// [special]p1). This routine can only be executed just before the
5047/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005048void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005049 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005050 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005051
Douglas Gregor54be3392010-07-01 17:57:27 +00005052 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00005053 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005054
Richard Smith966c1fb2011-12-24 21:56:24 +00005055 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5056 ++ASTContext::NumImplicitMoveConstructors;
5057
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005058 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5059 ++ASTContext::NumImplicitCopyAssignmentOperators;
5060
5061 // If we have a dynamic class, then the copy assignment operator may be
5062 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5063 // it shows up in the right place in the vtable and that we diagnose
5064 // problems with the implicit exception specification.
5065 if (ClassDecl->isDynamicClass())
5066 DeclareImplicitCopyAssignment(ClassDecl);
5067 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005068
Richard Smith966c1fb2011-12-24 21:56:24 +00005069 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5070 ++ASTContext::NumImplicitMoveAssignmentOperators;
5071
5072 // Likewise for the move assignment operator.
5073 if (ClassDecl->isDynamicClass())
5074 DeclareImplicitMoveAssignment(ClassDecl);
5075 }
5076
Douglas Gregor7454c562010-07-02 20:37:36 +00005077 if (!ClassDecl->hasUserDeclaredDestructor()) {
5078 ++ASTContext::NumImplicitDestructors;
5079
5080 // If we have a dynamic class, then the destructor may be virtual, so we
5081 // have to declare the destructor immediately. This ensures that, e.g., it
5082 // shows up in the right place in the vtable and that we diagnose problems
5083 // with the implicit exception specification.
5084 if (ClassDecl->isDynamicClass())
5085 DeclareImplicitDestructor(ClassDecl);
5086 }
Douglas Gregor05379422008-11-03 17:51:48 +00005087}
5088
Francois Pichet1c229c02011-04-22 22:18:13 +00005089void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5090 if (!D)
5091 return;
5092
5093 int NumParamList = D->getNumTemplateParameterLists();
5094 for (int i = 0; i < NumParamList; i++) {
5095 TemplateParameterList* Params = D->getTemplateParameterList(i);
5096 for (TemplateParameterList::iterator Param = Params->begin(),
5097 ParamEnd = Params->end();
5098 Param != ParamEnd; ++Param) {
5099 NamedDecl *Named = cast<NamedDecl>(*Param);
5100 if (Named->getDeclName()) {
5101 S->AddDecl(Named);
5102 IdResolver.AddDecl(Named);
5103 }
5104 }
5105 }
5106}
5107
John McCall48871652010-08-21 09:40:31 +00005108void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005109 if (!D)
5110 return;
5111
5112 TemplateParameterList *Params = 0;
5113 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5114 Params = Template->getTemplateParameters();
5115 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5116 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5117 Params = PartialSpec->getTemplateParameters();
5118 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005119 return;
5120
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005121 for (TemplateParameterList::iterator Param = Params->begin(),
5122 ParamEnd = Params->end();
5123 Param != ParamEnd; ++Param) {
5124 NamedDecl *Named = cast<NamedDecl>(*Param);
5125 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005126 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005127 IdResolver.AddDecl(Named);
5128 }
5129 }
5130}
5131
John McCall48871652010-08-21 09:40:31 +00005132void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005133 if (!RecordD) return;
5134 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005135 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005136 PushDeclContext(S, Record);
5137}
5138
John McCall48871652010-08-21 09:40:31 +00005139void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005140 if (!RecordD) return;
5141 PopDeclContext();
5142}
5143
Douglas Gregor4d87df52008-12-16 21:30:33 +00005144/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5145/// parsing a top-level (non-nested) C++ class, and we are now
5146/// parsing those parts of the given Method declaration that could
5147/// not be parsed earlier (C++ [class.mem]p2), such as default
5148/// arguments. This action should enter the scope of the given
5149/// Method declaration as if we had just parsed the qualified method
5150/// name. However, it should not bring the parameters into scope;
5151/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005152void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005153}
5154
5155/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5156/// C++ method declaration. We're (re-)introducing the given
5157/// function parameter into scope for use in parsing later parts of
5158/// the method declaration. For example, we could see an
5159/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00005160void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005161 if (!ParamD)
5162 return;
Mike Stump11289f42009-09-09 15:08:12 +00005163
John McCall48871652010-08-21 09:40:31 +00005164 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00005165
5166 // If this parameter has an unparsed default argument, clear it out
5167 // to make way for the parsed default argument.
5168 if (Param->hasUnparsedDefaultArg())
5169 Param->setDefaultArg(0);
5170
John McCall48871652010-08-21 09:40:31 +00005171 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005172 if (Param->getDeclName())
5173 IdResolver.AddDecl(Param);
5174}
5175
5176/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5177/// processing the delayed method declaration for Method. The method
5178/// declaration is now considered finished. There may be a separate
5179/// ActOnStartOfFunctionDef action later (not necessarily
5180/// immediately!) for this method, if it was also defined inside the
5181/// class body.
John McCall48871652010-08-21 09:40:31 +00005182void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005183 if (!MethodD)
5184 return;
Mike Stump11289f42009-09-09 15:08:12 +00005185
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005186 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005187
John McCall48871652010-08-21 09:40:31 +00005188 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005189
5190 // Now that we have our default arguments, check the constructor
5191 // again. It could produce additional diagnostics or affect whether
5192 // the class has implicitly-declared destructors, among other
5193 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005194 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5195 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005196
5197 // Check the default arguments, which we may have added.
5198 if (!Method->isInvalidDecl())
5199 CheckCXXDefaultArguments(Method);
5200}
5201
Douglas Gregor831c93f2008-11-05 20:51:48 +00005202/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005203/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005204/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005205/// emit diagnostics and set the invalid bit to true. In any case, the type
5206/// will be updated to reflect a well-formed type for the constructor and
5207/// returned.
5208QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005209 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005210 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005211
5212 // C++ [class.ctor]p3:
5213 // A constructor shall not be virtual (10.3) or static (9.4). A
5214 // constructor can be invoked for a const, volatile or const
5215 // volatile object. A constructor shall not be declared const,
5216 // volatile, or const volatile (9.3.2).
5217 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005218 if (!D.isInvalidType())
5219 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5220 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5221 << SourceRange(D.getIdentifierLoc());
5222 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005223 }
John McCall8e7d6562010-08-26 03:08:43 +00005224 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005225 if (!D.isInvalidType())
5226 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5227 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5228 << SourceRange(D.getIdentifierLoc());
5229 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005230 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005231 }
Mike Stump11289f42009-09-09 15:08:12 +00005232
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005233 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005234 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005235 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005236 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5237 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005238 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005239 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5240 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005241 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005242 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5243 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005244 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005245 }
Mike Stump11289f42009-09-09 15:08:12 +00005246
Douglas Gregordb9d6642011-01-26 05:01:58 +00005247 // C++0x [class.ctor]p4:
5248 // A constructor shall not be declared with a ref-qualifier.
5249 if (FTI.hasRefQualifier()) {
5250 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5251 << FTI.RefQualifierIsLValueRef
5252 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5253 D.setInvalidType();
5254 }
5255
Douglas Gregor831c93f2008-11-05 20:51:48 +00005256 // Rebuild the function type "R" without any type qualifiers (in
5257 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005258 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005259 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005260 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5261 return R;
5262
5263 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5264 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005265 EPI.RefQualifier = RQ_None;
5266
Chris Lattner38378bf2009-04-25 08:28:21 +00005267 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005268 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005269}
5270
Douglas Gregor4d87df52008-12-16 21:30:33 +00005271/// CheckConstructor - Checks a fully-formed constructor for
5272/// well-formedness, issuing any diagnostics required. Returns true if
5273/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005274void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005275 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005276 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5277 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005278 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005279
5280 // C++ [class.copy]p3:
5281 // A declaration of a constructor for a class X is ill-formed if
5282 // its first parameter is of type (optionally cv-qualified) X and
5283 // either there are no other parameters or else all other
5284 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005285 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005286 ((Constructor->getNumParams() == 1) ||
5287 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005288 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5289 Constructor->getTemplateSpecializationKind()
5290 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005291 QualType ParamType = Constructor->getParamDecl(0)->getType();
5292 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5293 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005294 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005295 const char *ConstRef
5296 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5297 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005298 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005299 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005300
5301 // FIXME: Rather that making the constructor invalid, we should endeavor
5302 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005303 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005304 }
5305 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005306}
5307
John McCalldeb646e2010-08-04 01:04:25 +00005308/// CheckDestructor - Checks a fully-formed destructor definition for
5309/// well-formedness, issuing any diagnostics required. Returns true
5310/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005311bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005312 CXXRecordDecl *RD = Destructor->getParent();
5313
5314 if (Destructor->isVirtual()) {
5315 SourceLocation Loc;
5316
5317 if (!Destructor->isImplicit())
5318 Loc = Destructor->getLocation();
5319 else
5320 Loc = RD->getLocation();
5321
5322 // If we have a virtual destructor, look up the deallocation function
5323 FunctionDecl *OperatorDelete = 0;
5324 DeclarationName Name =
5325 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005326 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005327 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005328
Eli Friedmanfa0df832012-02-02 03:46:19 +00005329 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005330
5331 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005332 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005333
5334 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005335}
5336
Mike Stump11289f42009-09-09 15:08:12 +00005337static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005338FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5339 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5340 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005341 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005342}
5343
Douglas Gregor831c93f2008-11-05 20:51:48 +00005344/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5345/// the well-formednes of the destructor declarator @p D with type @p
5346/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005347/// emit diagnostics and set the declarator to invalid. Even if this happens,
5348/// will be updated to reflect a well-formed type for the destructor and
5349/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005350QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005351 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005352 // C++ [class.dtor]p1:
5353 // [...] A typedef-name that names a class is a class-name
5354 // (7.1.3); however, a typedef-name that names a class shall not
5355 // be used as the identifier in the declarator for a destructor
5356 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005357 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005358 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005359 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005360 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005361 else if (const TemplateSpecializationType *TST =
5362 DeclaratorType->getAs<TemplateSpecializationType>())
5363 if (TST->isTypeAlias())
5364 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5365 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005366
5367 // C++ [class.dtor]p2:
5368 // A destructor is used to destroy objects of its class type. A
5369 // destructor takes no parameters, and no return type can be
5370 // specified for it (not even void). The address of a destructor
5371 // shall not be taken. A destructor shall not be static. A
5372 // destructor can be invoked for a const, volatile or const
5373 // volatile object. A destructor shall not be declared const,
5374 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005375 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005376 if (!D.isInvalidType())
5377 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5378 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005379 << SourceRange(D.getIdentifierLoc())
5380 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5381
John McCall8e7d6562010-08-26 03:08:43 +00005382 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005383 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005384 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005385 // Destructors don't have return types, but the parser will
5386 // happily parse something like:
5387 //
5388 // class X {
5389 // float ~X();
5390 // };
5391 //
5392 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005393 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5394 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5395 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005396 }
Mike Stump11289f42009-09-09 15:08:12 +00005397
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005398 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005399 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005400 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005401 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5402 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005403 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005404 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5405 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005406 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005407 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5408 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005409 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005410 }
5411
Douglas Gregordb9d6642011-01-26 05:01:58 +00005412 // C++0x [class.dtor]p2:
5413 // A destructor shall not be declared with a ref-qualifier.
5414 if (FTI.hasRefQualifier()) {
5415 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5416 << FTI.RefQualifierIsLValueRef
5417 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5418 D.setInvalidType();
5419 }
5420
Douglas Gregor831c93f2008-11-05 20:51:48 +00005421 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005422 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005423 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5424
5425 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005426 FTI.freeArgs();
5427 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005428 }
5429
Mike Stump11289f42009-09-09 15:08:12 +00005430 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005431 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005432 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005433 D.setInvalidType();
5434 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005435
5436 // Rebuild the function type "R" without any type qualifiers or
5437 // parameters (in case any of the errors above fired) and with
5438 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005439 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005440 if (!D.isInvalidType())
5441 return R;
5442
Douglas Gregor95755162010-07-01 05:10:53 +00005443 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005444 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5445 EPI.Variadic = false;
5446 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005447 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005448 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005449}
5450
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005451/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5452/// well-formednes of the conversion function declarator @p D with
5453/// type @p R. If there are any errors in the declarator, this routine
5454/// will emit diagnostics and return true. Otherwise, it will return
5455/// false. Either way, the type @p R will be updated to reflect a
5456/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005457void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005458 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005459 // C++ [class.conv.fct]p1:
5460 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005461 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005462 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005463 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005464 if (!D.isInvalidType())
5465 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5466 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5467 << SourceRange(D.getIdentifierLoc());
5468 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005469 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005470 }
John McCall212fa2e2010-04-13 00:04:31 +00005471
5472 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5473
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005474 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005475 // Conversion functions don't have return types, but the parser will
5476 // happily parse something like:
5477 //
5478 // class X {
5479 // float operator bool();
5480 // };
5481 //
5482 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005483 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5484 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5485 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005486 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005487 }
5488
John McCall212fa2e2010-04-13 00:04:31 +00005489 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5490
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005491 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005492 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005493 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5494
5495 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005496 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005497 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005498 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005499 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005500 D.setInvalidType();
5501 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005502
John McCall212fa2e2010-04-13 00:04:31 +00005503 // Diagnose "&operator bool()" and other such nonsense. This
5504 // is actually a gcc extension which we don't support.
5505 if (Proto->getResultType() != ConvType) {
5506 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5507 << Proto->getResultType();
5508 D.setInvalidType();
5509 ConvType = Proto->getResultType();
5510 }
5511
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005512 // C++ [class.conv.fct]p4:
5513 // The conversion-type-id shall not represent a function type nor
5514 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005515 if (ConvType->isArrayType()) {
5516 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5517 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005518 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005519 } else if (ConvType->isFunctionType()) {
5520 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5521 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005522 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005523 }
5524
5525 // Rebuild the function type "R" without any parameters (in case any
5526 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005527 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005528 if (D.isInvalidType())
5529 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005530
Douglas Gregor5fb53972009-01-14 15:45:31 +00005531 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005532 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00005533 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith0bf8a4922011-10-18 20:49:44 +00005534 getLangOptions().CPlusPlus0x ?
5535 diag::warn_cxx98_compat_explicit_conversion_functions :
5536 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00005537 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005538}
5539
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005540/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5541/// the declaration of the given C++ conversion function. This routine
5542/// is responsible for recording the conversion function in the C++
5543/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005544Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005545 assert(Conversion && "Expected to receive a conversion function declaration");
5546
Douglas Gregor4287b372008-12-12 08:25:50 +00005547 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005548
5549 // Make sure we aren't redeclaring the conversion function.
5550 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005551
5552 // C++ [class.conv.fct]p1:
5553 // [...] A conversion function is never used to convert a
5554 // (possibly cv-qualified) object to the (possibly cv-qualified)
5555 // same object type (or a reference to it), to a (possibly
5556 // cv-qualified) base class of that type (or a reference to it),
5557 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005558 // FIXME: Suppress this warning if the conversion function ends up being a
5559 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005560 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005561 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005562 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005563 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005564 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5565 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005566 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005567 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005568 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5569 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005570 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005571 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005572 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005573 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005574 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005575 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005576 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005577 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005578 }
5579
Douglas Gregor457104e2010-09-29 04:25:11 +00005580 if (FunctionTemplateDecl *ConversionTemplate
5581 = Conversion->getDescribedFunctionTemplate())
5582 return ConversionTemplate;
5583
John McCall48871652010-08-21 09:40:31 +00005584 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005585}
5586
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005587//===----------------------------------------------------------------------===//
5588// Namespace Handling
5589//===----------------------------------------------------------------------===//
5590
John McCallb1be5232010-08-26 09:15:37 +00005591
5592
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005593/// ActOnStartNamespaceDef - This is called at the start of a namespace
5594/// definition.
John McCall48871652010-08-21 09:40:31 +00005595Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005596 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005597 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005598 SourceLocation IdentLoc,
5599 IdentifierInfo *II,
5600 SourceLocation LBrace,
5601 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005602 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5603 // For anonymous namespace, take the location of the left brace.
5604 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00005605 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00005606 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00005607 bool IsStd = false;
5608 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005609 Scope *DeclRegionScope = NamespcScope->getParent();
5610
Douglas Gregore57e7522012-01-07 09:11:48 +00005611 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005612 if (II) {
5613 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005614 // The identifier in an original-namespace-definition shall not
5615 // have been previously defined in the declarative region in
5616 // which the original-namespace-definition appears. The
5617 // identifier in an original-namespace-definition is the name of
5618 // the namespace. Subsequently in that declarative region, it is
5619 // treated as an original-namespace-name.
5620 //
5621 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005622 // look through using directives, just look for any ordinary names.
5623
5624 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00005625 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5626 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005627 NamedDecl *PrevDecl = 0;
5628 for (DeclContext::lookup_result R
Douglas Gregore57e7522012-01-07 09:11:48 +00005629 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005630 R.first != R.second; ++R.first) {
5631 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5632 PrevDecl = *R.first;
5633 break;
5634 }
5635 }
5636
Douglas Gregore57e7522012-01-07 09:11:48 +00005637 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5638
5639 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00005640 // This is an extended namespace definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005641 if (IsInline != PrevNS->isInline()) {
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005642 // inline-ness must match
Douglas Gregore57e7522012-01-07 09:11:48 +00005643 if (PrevNS->isInline()) {
Douglas Gregora9121972011-05-20 15:48:31 +00005644 // The user probably just forgot the 'inline', so suggest that it
5645 // be added back.
Douglas Gregore57e7522012-01-07 09:11:48 +00005646 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregora9121972011-05-20 15:48:31 +00005647 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5648 } else {
Douglas Gregore57e7522012-01-07 09:11:48 +00005649 Diag(Loc, diag::err_inline_namespace_mismatch)
5650 << IsInline;
Douglas Gregora9121972011-05-20 15:48:31 +00005651 }
Douglas Gregore57e7522012-01-07 09:11:48 +00005652 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5653
5654 IsInline = PrevNS->isInline();
5655 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005656 } else if (PrevDecl) {
5657 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005658 Diag(Loc, diag::err_redefinition_different_kind)
5659 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00005660 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005661 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00005662 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00005663 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005664 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005665 // This is the first "real" definition of the namespace "std", so update
5666 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005667 PrevNS = getStdNamespace();
5668 IsStd = true;
5669 AddToKnown = !IsInline;
5670 } else {
5671 // We've seen this namespace for the first time.
5672 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00005673 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005674 } else {
John McCall4fa53422009-10-01 00:25:31 +00005675 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00005676
5677 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00005678 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005679 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00005680 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005681 } else {
5682 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00005683 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005684 }
5685
Douglas Gregore57e7522012-01-07 09:11:48 +00005686 if (PrevNS && IsInline != PrevNS->isInline()) {
5687 // inline-ness must match
5688 Diag(Loc, diag::err_inline_namespace_mismatch)
5689 << IsInline;
5690 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005691
Douglas Gregore57e7522012-01-07 09:11:48 +00005692 // Recover by ignoring the new namespace's inline status.
5693 IsInline = PrevNS->isInline();
5694 }
5695 }
5696
5697 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5698 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005699 if (IsInvalid)
5700 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00005701
5702 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005703
Douglas Gregore57e7522012-01-07 09:11:48 +00005704 // FIXME: Should we be merging attributes?
5705 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005706 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00005707
5708 if (IsStd)
5709 StdNamespace = Namespc;
5710 if (AddToKnown)
5711 KnownNamespaces[Namespc] = false;
5712
5713 if (II) {
5714 PushOnScopeChains(Namespc, DeclRegionScope);
5715 } else {
5716 // Link the anonymous namespace into its parent.
5717 DeclContext *Parent = CurContext->getRedeclContext();
5718 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5719 TU->setAnonymousNamespace(Namespc);
5720 } else {
5721 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00005722 }
John McCall4fa53422009-10-01 00:25:31 +00005723
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005724 CurContext->addDecl(Namespc);
5725
John McCall4fa53422009-10-01 00:25:31 +00005726 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5727 // behaves as if it were replaced by
5728 // namespace unique { /* empty body */ }
5729 // using namespace unique;
5730 // namespace unique { namespace-body }
5731 // where all occurrences of 'unique' in a translation unit are
5732 // replaced by the same identifier and this identifier differs
5733 // from all other identifiers in the entire program.
5734
5735 // We just create the namespace with an empty name and then add an
5736 // implicit using declaration, just like the standard suggests.
5737 //
5738 // CodeGen enforces the "universally unique" aspect by giving all
5739 // declarations semantically contained within an anonymous
5740 // namespace internal linkage.
5741
Douglas Gregore57e7522012-01-07 09:11:48 +00005742 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00005743 UsingDirectiveDecl* UD
5744 = UsingDirectiveDecl::Create(Context, CurContext,
5745 /* 'using' */ LBrace,
5746 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005747 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005748 /* identifier */ SourceLocation(),
5749 Namespc,
5750 /* Ancestor */ CurContext);
5751 UD->setImplicit();
5752 CurContext->addDecl(UD);
5753 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005754 }
5755
5756 // Although we could have an invalid decl (i.e. the namespace name is a
5757 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005758 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5759 // for the namespace has the declarations that showed up in that particular
5760 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005761 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005762 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005763}
5764
Sebastian Redla6602e92009-11-23 15:34:23 +00005765/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5766/// is a namespace alias, returns the namespace it points to.
5767static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5768 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5769 return AD->getNamespace();
5770 return dyn_cast_or_null<NamespaceDecl>(D);
5771}
5772
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005773/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5774/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005775void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005776 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5777 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005778 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005779 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005780 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005781 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005782}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005783
John McCall28a0cf72010-08-25 07:42:41 +00005784CXXRecordDecl *Sema::getStdBadAlloc() const {
5785 return cast_or_null<CXXRecordDecl>(
5786 StdBadAlloc.get(Context.getExternalSource()));
5787}
5788
5789NamespaceDecl *Sema::getStdNamespace() const {
5790 return cast_or_null<NamespaceDecl>(
5791 StdNamespace.get(Context.getExternalSource()));
5792}
5793
Douglas Gregorcdf87022010-06-29 17:53:46 +00005794/// \brief Retrieve the special "std" namespace, which may require us to
5795/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005796NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005797 if (!StdNamespace) {
5798 // The "std" namespace has not yet been defined, so build one implicitly.
5799 StdNamespace = NamespaceDecl::Create(Context,
5800 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005801 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005802 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005803 &PP.getIdentifierTable().get("std"),
5804 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005805 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005806 }
5807
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005808 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005809}
5810
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005811bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5812 assert(getLangOptions().CPlusPlus &&
5813 "Looking for std::initializer_list outside of C++.");
5814
5815 // We're looking for implicit instantiations of
5816 // template <typename E> class std::initializer_list.
5817
5818 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5819 return false;
5820
Sebastian Redl43144e72012-01-17 22:49:58 +00005821 ClassTemplateDecl *Template = 0;
5822 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005823
Sebastian Redl43144e72012-01-17 22:49:58 +00005824 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005825
Sebastian Redl43144e72012-01-17 22:49:58 +00005826 ClassTemplateSpecializationDecl *Specialization =
5827 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5828 if (!Specialization)
5829 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005830
Sebastian Redl43144e72012-01-17 22:49:58 +00005831 Template = Specialization->getSpecializedTemplate();
5832 Arguments = Specialization->getTemplateArgs().data();
5833 } else if (const TemplateSpecializationType *TST =
5834 Ty->getAs<TemplateSpecializationType>()) {
5835 Template = dyn_cast_or_null<ClassTemplateDecl>(
5836 TST->getTemplateName().getAsTemplateDecl());
5837 Arguments = TST->getArgs();
5838 }
5839 if (!Template)
5840 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005841
5842 if (!StdInitializerList) {
5843 // Haven't recognized std::initializer_list yet, maybe this is it.
5844 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5845 if (TemplateClass->getIdentifier() !=
5846 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00005847 !getStdNamespace()->InEnclosingNamespaceSetOf(
5848 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005849 return false;
5850 // This is a template called std::initializer_list, but is it the right
5851 // template?
5852 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005853 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005854 return false;
5855 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5856 return false;
5857
5858 // It's the right template.
5859 StdInitializerList = Template;
5860 }
5861
5862 if (Template != StdInitializerList)
5863 return false;
5864
5865 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00005866 if (Element)
5867 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005868 return true;
5869}
5870
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005871static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5872 NamespaceDecl *Std = S.getStdNamespace();
5873 if (!Std) {
5874 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5875 return 0;
5876 }
5877
5878 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5879 Loc, Sema::LookupOrdinaryName);
5880 if (!S.LookupQualifiedName(Result, Std)) {
5881 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5882 return 0;
5883 }
5884 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5885 if (!Template) {
5886 Result.suppressDiagnostics();
5887 // We found something weird. Complain about the first thing we found.
5888 NamedDecl *Found = *Result.begin();
5889 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5890 return 0;
5891 }
5892
5893 // We found some template called std::initializer_list. Now verify that it's
5894 // correct.
5895 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005896 if (Params->getMinRequiredArguments() != 1 ||
5897 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005898 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5899 return 0;
5900 }
5901
5902 return Template;
5903}
5904
5905QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5906 if (!StdInitializerList) {
5907 StdInitializerList = LookupStdInitializerList(*this, Loc);
5908 if (!StdInitializerList)
5909 return QualType();
5910 }
5911
5912 TemplateArgumentListInfo Args(Loc, Loc);
5913 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5914 Context.getTrivialTypeSourceInfo(Element,
5915 Loc)));
5916 return Context.getCanonicalType(
5917 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5918}
5919
Sebastian Redlbe24ec22012-01-17 22:50:14 +00005920bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5921 // C++ [dcl.init.list]p2:
5922 // A constructor is an initializer-list constructor if its first parameter
5923 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5924 // std::initializer_list<E> for some type E, and either there are no other
5925 // parameters or else all other parameters have default arguments.
5926 if (Ctor->getNumParams() < 1 ||
5927 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5928 return false;
5929
5930 QualType ArgType = Ctor->getParamDecl(0)->getType();
5931 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5932 ArgType = RT->getPointeeType().getUnqualifiedType();
5933
5934 return isStdInitializerList(ArgType, 0);
5935}
5936
Douglas Gregora172e082011-03-26 22:25:30 +00005937/// \brief Determine whether a using statement is in a context where it will be
5938/// apply in all contexts.
5939static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5940 switch (CurContext->getDeclKind()) {
5941 case Decl::TranslationUnit:
5942 return true;
5943 case Decl::LinkageSpec:
5944 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5945 default:
5946 return false;
5947 }
5948}
5949
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005950namespace {
5951
5952// Callback to only accept typo corrections that are namespaces.
5953class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5954 public:
5955 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5956 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5957 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5958 }
5959 return false;
5960 }
5961};
5962
5963}
5964
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005965static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5966 CXXScopeSpec &SS,
5967 SourceLocation IdentLoc,
5968 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005969 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005970 R.clear();
5971 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005972 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00005973 Validator)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005974 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5975 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5976 if (DeclContext *DC = S.computeDeclContext(SS, false))
5977 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5978 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5979 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5980 else
5981 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5982 << Ident << CorrectedQuotedStr
5983 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005984
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005985 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5986 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005987
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005988 Ident = Corrected.getCorrectionAsIdentifierInfo();
5989 R.addDecl(Corrected.getCorrectionDecl());
5990 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005991 }
5992 return false;
5993}
5994
John McCall48871652010-08-21 09:40:31 +00005995Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005996 SourceLocation UsingLoc,
5997 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005998 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005999 SourceLocation IdentLoc,
6000 IdentifierInfo *NamespcName,
6001 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006002 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6003 assert(NamespcName && "Invalid NamespcName.");
6004 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006005
6006 // This can only happen along a recovery path.
6007 while (S->getFlags() & Scope::TemplateParamScope)
6008 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006009 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006010
Douglas Gregor889ceb72009-02-03 19:21:40 +00006011 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006012 NestedNameSpecifier *Qualifier = 0;
6013 if (SS.isSet())
6014 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6015
Douglas Gregor34074322009-01-14 22:20:51 +00006016 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006017 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6018 LookupParsedName(R, S, &SS);
6019 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006020 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006021
Douglas Gregorcdf87022010-06-29 17:53:46 +00006022 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006023 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006024 // Allow "using namespace std;" or "using namespace ::std;" even if
6025 // "std" hasn't been defined yet, for GCC compatibility.
6026 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6027 NamespcName->isStr("std")) {
6028 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006029 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006030 R.resolveKind();
6031 }
6032 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006033 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006034 }
6035
John McCall9f3059a2009-10-09 21:13:30 +00006036 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006037 NamedDecl *Named = R.getFoundDecl();
6038 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6039 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006040 // C++ [namespace.udir]p1:
6041 // A using-directive specifies that the names in the nominated
6042 // namespace can be used in the scope in which the
6043 // using-directive appears after the using-directive. During
6044 // unqualified name lookup (3.4.1), the names appear as if they
6045 // were declared in the nearest enclosing namespace which
6046 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006047 // namespace. [Note: in this context, "contains" means "contains
6048 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006049
6050 // Find enclosing context containing both using-directive and
6051 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006052 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006053 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6054 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6055 CommonAncestor = CommonAncestor->getParent();
6056
Sebastian Redla6602e92009-11-23 15:34:23 +00006057 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006058 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006059 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006060
Douglas Gregora172e082011-03-26 22:25:30 +00006061 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00006062 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006063 Diag(IdentLoc, diag::warn_using_directive_in_header);
6064 }
6065
Douglas Gregor889ceb72009-02-03 19:21:40 +00006066 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006067 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006068 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006069 }
6070
Douglas Gregor889ceb72009-02-03 19:21:40 +00006071 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00006072 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006073}
6074
6075void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6076 // If scope has associated entity, then using directive is at namespace
6077 // or translation unit scope. We add UsingDirectiveDecls, into
6078 // it's lookup structure.
6079 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006080 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006081 else
6082 // Otherwise it is block-sope. using-directives will affect lookup
6083 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00006084 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006085}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006086
Douglas Gregorfec52632009-06-20 00:51:54 +00006087
John McCall48871652010-08-21 09:40:31 +00006088Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006089 AccessSpecifier AS,
6090 bool HasUsingKeyword,
6091 SourceLocation UsingLoc,
6092 CXXScopeSpec &SS,
6093 UnqualifiedId &Name,
6094 AttributeList *AttrList,
6095 bool IsTypeName,
6096 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006097 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006098
Douglas Gregor220f4272009-11-04 16:30:06 +00006099 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006100 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006101 case UnqualifiedId::IK_Identifier:
6102 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006103 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006104 case UnqualifiedId::IK_ConversionFunctionId:
6105 break;
6106
6107 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00006108 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00006109 // C++0x inherited constructors.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006110 Diag(Name.getSourceRange().getBegin(),
6111 getLangOptions().CPlusPlus0x ?
6112 diag::warn_cxx98_compat_using_decl_constructor :
6113 diag::err_using_decl_constructor)
6114 << SS.getRange();
6115
John McCall3969e302009-12-08 07:46:18 +00006116 if (getLangOptions().CPlusPlus0x) break;
6117
John McCall48871652010-08-21 09:40:31 +00006118 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006119
6120 case UnqualifiedId::IK_DestructorName:
6121 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6122 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006123 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006124
6125 case UnqualifiedId::IK_TemplateId:
6126 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6127 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006128 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006129 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006130
6131 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6132 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006133 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00006134 return 0;
John McCall3969e302009-12-08 07:46:18 +00006135
John McCalla0097262009-12-11 02:10:03 +00006136 // Warn about using declarations.
6137 // TODO: store that the declaration was written without 'using' and
6138 // talk about access decls instead of using decls in the
6139 // diagnostics.
6140 if (!HasUsingKeyword) {
6141 UsingLoc = Name.getSourceRange().getBegin();
6142
6143 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00006144 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00006145 }
6146
Douglas Gregorc4356532010-12-16 00:46:58 +00006147 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6148 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6149 return 0;
6150
John McCall3f746822009-11-17 05:59:44 +00006151 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006152 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006153 /* IsInstantiation */ false,
6154 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00006155 if (UD)
6156 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00006157
John McCall48871652010-08-21 09:40:31 +00006158 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00006159}
6160
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006161/// \brief Determine whether a using declaration considers the given
6162/// declarations as "equivalent", e.g., if they are redeclarations of
6163/// the same entity or are both typedefs of the same type.
6164static bool
6165IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6166 bool &SuppressRedeclaration) {
6167 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6168 SuppressRedeclaration = false;
6169 return true;
6170 }
6171
Richard Smithdda56e42011-04-15 14:24:37 +00006172 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6173 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006174 SuppressRedeclaration = true;
6175 return Context.hasSameType(TD1->getUnderlyingType(),
6176 TD2->getUnderlyingType());
6177 }
6178
6179 return false;
6180}
6181
6182
John McCall84d87672009-12-10 09:41:52 +00006183/// Determines whether to create a using shadow decl for a particular
6184/// decl, given the set of decls existing prior to this using lookup.
6185bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6186 const LookupResult &Previous) {
6187 // Diagnose finding a decl which is not from a base class of the
6188 // current class. We do this now because there are cases where this
6189 // function will silently decide not to build a shadow decl, which
6190 // will pre-empt further diagnostics.
6191 //
6192 // We don't need to do this in C++0x because we do the check once on
6193 // the qualifier.
6194 //
6195 // FIXME: diagnose the following if we care enough:
6196 // struct A { int foo; };
6197 // struct B : A { using A::foo; };
6198 // template <class T> struct C : A {};
6199 // template <class T> struct D : C<T> { using B::foo; } // <---
6200 // This is invalid (during instantiation) in C++03 because B::foo
6201 // resolves to the using decl in B, which is not a base class of D<T>.
6202 // We can't diagnose it immediately because C<T> is an unknown
6203 // specialization. The UsingShadowDecl in D<T> then points directly
6204 // to A::foo, which will look well-formed when we instantiate.
6205 // The right solution is to not collapse the shadow-decl chain.
6206 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6207 DeclContext *OrigDC = Orig->getDeclContext();
6208
6209 // Handle enums and anonymous structs.
6210 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6211 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6212 while (OrigRec->isAnonymousStructOrUnion())
6213 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6214
6215 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6216 if (OrigDC == CurContext) {
6217 Diag(Using->getLocation(),
6218 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006219 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006220 Diag(Orig->getLocation(), diag::note_using_decl_target);
6221 return true;
6222 }
6223
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006224 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00006225 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006226 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00006227 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006228 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006229 Diag(Orig->getLocation(), diag::note_using_decl_target);
6230 return true;
6231 }
6232 }
6233
6234 if (Previous.empty()) return false;
6235
6236 NamedDecl *Target = Orig;
6237 if (isa<UsingShadowDecl>(Target))
6238 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6239
John McCalla17e83e2009-12-11 02:33:26 +00006240 // If the target happens to be one of the previous declarations, we
6241 // don't have a conflict.
6242 //
6243 // FIXME: but we might be increasing its access, in which case we
6244 // should redeclare it.
6245 NamedDecl *NonTag = 0, *Tag = 0;
6246 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6247 I != E; ++I) {
6248 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006249 bool Result;
6250 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6251 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00006252
6253 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6254 }
6255
John McCall84d87672009-12-10 09:41:52 +00006256 if (Target->isFunctionOrFunctionTemplate()) {
6257 FunctionDecl *FD;
6258 if (isa<FunctionTemplateDecl>(Target))
6259 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6260 else
6261 FD = cast<FunctionDecl>(Target);
6262
6263 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00006264 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00006265 case Ovl_Overload:
6266 return false;
6267
6268 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00006269 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006270 break;
6271
6272 // We found a decl with the exact signature.
6273 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006274 // If we're in a record, we want to hide the target, so we
6275 // return true (without a diagnostic) to tell the caller not to
6276 // build a shadow decl.
6277 if (CurContext->isRecord())
6278 return true;
6279
6280 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00006281 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006282 break;
6283 }
6284
6285 Diag(Target->getLocation(), diag::note_using_decl_target);
6286 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6287 return true;
6288 }
6289
6290 // Target is not a function.
6291
John McCall84d87672009-12-10 09:41:52 +00006292 if (isa<TagDecl>(Target)) {
6293 // No conflict between a tag and a non-tag.
6294 if (!Tag) return false;
6295
John McCalle29c5cd2009-12-10 19:51:03 +00006296 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006297 Diag(Target->getLocation(), diag::note_using_decl_target);
6298 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6299 return true;
6300 }
6301
6302 // No conflict between a tag and a non-tag.
6303 if (!NonTag) return false;
6304
John McCalle29c5cd2009-12-10 19:51:03 +00006305 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006306 Diag(Target->getLocation(), diag::note_using_decl_target);
6307 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6308 return true;
6309}
6310
John McCall3f746822009-11-17 05:59:44 +00006311/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00006312UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00006313 UsingDecl *UD,
6314 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00006315
6316 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00006317 NamedDecl *Target = Orig;
6318 if (isa<UsingShadowDecl>(Target)) {
6319 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6320 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006321 }
6322
6323 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006324 = UsingShadowDecl::Create(Context, CurContext,
6325 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006326 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006327
6328 Shadow->setAccess(UD->getAccess());
6329 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6330 Shadow->setInvalidDecl();
6331
John McCall3f746822009-11-17 05:59:44 +00006332 if (S)
John McCall3969e302009-12-08 07:46:18 +00006333 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006334 else
John McCall3969e302009-12-08 07:46:18 +00006335 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006336
John McCall3969e302009-12-08 07:46:18 +00006337
John McCall84d87672009-12-10 09:41:52 +00006338 return Shadow;
6339}
John McCall3969e302009-12-08 07:46:18 +00006340
John McCall84d87672009-12-10 09:41:52 +00006341/// Hides a using shadow declaration. This is required by the current
6342/// using-decl implementation when a resolvable using declaration in a
6343/// class is followed by a declaration which would hide or override
6344/// one or more of the using decl's targets; for example:
6345///
6346/// struct Base { void foo(int); };
6347/// struct Derived : Base {
6348/// using Base::foo;
6349/// void foo(int);
6350/// };
6351///
6352/// The governing language is C++03 [namespace.udecl]p12:
6353///
6354/// When a using-declaration brings names from a base class into a
6355/// derived class scope, member functions in the derived class
6356/// override and/or hide member functions with the same name and
6357/// parameter types in a base class (rather than conflicting).
6358///
6359/// There are two ways to implement this:
6360/// (1) optimistically create shadow decls when they're not hidden
6361/// by existing declarations, or
6362/// (2) don't create any shadow decls (or at least don't make them
6363/// visible) until we've fully parsed/instantiated the class.
6364/// The problem with (1) is that we might have to retroactively remove
6365/// a shadow decl, which requires several O(n) operations because the
6366/// decl structures are (very reasonably) not designed for removal.
6367/// (2) avoids this but is very fiddly and phase-dependent.
6368void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006369 if (Shadow->getDeclName().getNameKind() ==
6370 DeclarationName::CXXConversionFunctionName)
6371 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6372
John McCall84d87672009-12-10 09:41:52 +00006373 // Remove it from the DeclContext...
6374 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006375
John McCall84d87672009-12-10 09:41:52 +00006376 // ...and the scope, if applicable...
6377 if (S) {
John McCall48871652010-08-21 09:40:31 +00006378 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00006379 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006380 }
6381
John McCall84d87672009-12-10 09:41:52 +00006382 // ...and the using decl.
6383 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6384
6385 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00006386 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00006387}
6388
John McCalle61f2ba2009-11-18 02:36:19 +00006389/// Builds a using declaration.
6390///
6391/// \param IsInstantiation - Whether this call arises from an
6392/// instantiation of an unresolved using declaration. We treat
6393/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00006394NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6395 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006396 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006397 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00006398 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006399 bool IsInstantiation,
6400 bool IsTypeName,
6401 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00006402 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006403 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00006404 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00006405
Anders Carlssonf038fc22009-08-28 05:49:21 +00006406 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00006407
Anders Carlsson59140b32009-08-28 03:16:11 +00006408 if (SS.isEmpty()) {
6409 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00006410 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00006411 }
Mike Stump11289f42009-09-09 15:08:12 +00006412
John McCall84d87672009-12-10 09:41:52 +00006413 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006414 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00006415 ForRedeclaration);
6416 Previous.setHideTags(false);
6417 if (S) {
6418 LookupName(Previous, S);
6419
6420 // It is really dumb that we have to do this.
6421 LookupResult::Filter F = Previous.makeFilter();
6422 while (F.hasNext()) {
6423 NamedDecl *D = F.next();
6424 if (!isDeclInScope(D, CurContext, S))
6425 F.erase();
6426 }
6427 F.done();
6428 } else {
6429 assert(IsInstantiation && "no scope in non-instantiation");
6430 assert(CurContext->isRecord() && "scope not record in instantiation");
6431 LookupQualifiedName(Previous, CurContext);
6432 }
6433
John McCall84d87672009-12-10 09:41:52 +00006434 // Check for invalid redeclarations.
6435 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6436 return 0;
6437
6438 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00006439 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6440 return 0;
6441
John McCall84c16cf2009-11-12 03:15:40 +00006442 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006443 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006444 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00006445 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00006446 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00006447 // FIXME: not all declaration name kinds are legal here
6448 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6449 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006450 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006451 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00006452 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006453 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6454 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00006455 }
John McCallb96ec562009-12-04 22:46:56 +00006456 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006457 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6458 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00006459 }
John McCallb96ec562009-12-04 22:46:56 +00006460 D->setAccess(AS);
6461 CurContext->addDecl(D);
6462
6463 if (!LookupContext) return D;
6464 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00006465
John McCall0b66eb32010-05-01 00:40:08 +00006466 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00006467 UD->setInvalidDecl();
6468 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00006469 }
6470
Sebastian Redl08905022011-02-05 19:23:19 +00006471 // Constructor inheriting using decls get special treatment.
6472 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00006473 if (CheckInheritedConstructorUsingDecl(UD))
6474 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00006475 return UD;
6476 }
6477
6478 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00006479
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006480 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00006481
John McCall3969e302009-12-08 07:46:18 +00006482 // Unlike most lookups, we don't always want to hide tag
6483 // declarations: tag names are visible through the using declaration
6484 // even if hidden by ordinary names, *except* in a dependent context
6485 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00006486 if (!IsInstantiation)
6487 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00006488
John McCall27b18f82009-11-17 02:14:36 +00006489 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00006490
John McCall9f3059a2009-10-09 21:13:30 +00006491 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00006492 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006493 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006494 UD->setInvalidDecl();
6495 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006496 }
6497
John McCallb96ec562009-12-04 22:46:56 +00006498 if (R.isAmbiguous()) {
6499 UD->setInvalidDecl();
6500 return UD;
6501 }
Mike Stump11289f42009-09-09 15:08:12 +00006502
John McCalle61f2ba2009-11-18 02:36:19 +00006503 if (IsTypeName) {
6504 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00006505 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006506 Diag(IdentLoc, diag::err_using_typename_non_type);
6507 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6508 Diag((*I)->getUnderlyingDecl()->getLocation(),
6509 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006510 UD->setInvalidDecl();
6511 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006512 }
6513 } else {
6514 // If we asked for a non-typename and we got a type, error out,
6515 // but only if this is an instantiation of an unresolved using
6516 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00006517 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006518 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6519 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006520 UD->setInvalidDecl();
6521 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006522 }
Anders Carlsson59140b32009-08-28 03:16:11 +00006523 }
6524
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006525 // C++0x N2914 [namespace.udecl]p6:
6526 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00006527 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006528 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6529 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006530 UD->setInvalidDecl();
6531 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006532 }
Mike Stump11289f42009-09-09 15:08:12 +00006533
John McCall84d87672009-12-10 09:41:52 +00006534 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6535 if (!CheckUsingShadowDecl(UD, *I, Previous))
6536 BuildUsingShadowDecl(S, UD, *I);
6537 }
John McCall3f746822009-11-17 05:59:44 +00006538
6539 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006540}
6541
Sebastian Redl08905022011-02-05 19:23:19 +00006542/// Additional checks for a using declaration referring to a constructor name.
6543bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6544 if (UD->isTypeName()) {
6545 // FIXME: Cannot specify typename when specifying constructor
6546 return true;
6547 }
6548
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006549 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006550 assert(SourceType &&
6551 "Using decl naming constructor doesn't have type in scope spec.");
6552 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6553
6554 // Check whether the named type is a direct base class.
6555 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6556 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6557 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6558 BaseIt != BaseE; ++BaseIt) {
6559 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6560 if (CanonicalSourceType == BaseType)
6561 break;
6562 }
6563
6564 if (BaseIt == BaseE) {
6565 // Did not find SourceType in the bases.
6566 Diag(UD->getUsingLocation(),
6567 diag::err_using_decl_constructor_not_in_direct_base)
6568 << UD->getNameInfo().getSourceRange()
6569 << QualType(SourceType, 0) << TargetClass;
6570 return true;
6571 }
6572
6573 BaseIt->setInheritConstructors();
6574
6575 return false;
6576}
6577
John McCall84d87672009-12-10 09:41:52 +00006578/// Checks that the given using declaration is not an invalid
6579/// redeclaration. Note that this is checking only for the using decl
6580/// itself, not for any ill-formedness among the UsingShadowDecls.
6581bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6582 bool isTypeName,
6583 const CXXScopeSpec &SS,
6584 SourceLocation NameLoc,
6585 const LookupResult &Prev) {
6586 // C++03 [namespace.udecl]p8:
6587 // C++0x [namespace.udecl]p10:
6588 // A using-declaration is a declaration and can therefore be used
6589 // repeatedly where (and only where) multiple declarations are
6590 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006591 //
John McCall032092f2010-11-29 18:01:58 +00006592 // That's in non-member contexts.
6593 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006594 return false;
6595
6596 NestedNameSpecifier *Qual
6597 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6598
6599 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6600 NamedDecl *D = *I;
6601
6602 bool DTypename;
6603 NestedNameSpecifier *DQual;
6604 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6605 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006606 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006607 } else if (UnresolvedUsingValueDecl *UD
6608 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6609 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006610 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006611 } else if (UnresolvedUsingTypenameDecl *UD
6612 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6613 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006614 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006615 } else continue;
6616
6617 // using decls differ if one says 'typename' and the other doesn't.
6618 // FIXME: non-dependent using decls?
6619 if (isTypeName != DTypename) continue;
6620
6621 // using decls differ if they name different scopes (but note that
6622 // template instantiation can cause this check to trigger when it
6623 // didn't before instantiation).
6624 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6625 Context.getCanonicalNestedNameSpecifier(DQual))
6626 continue;
6627
6628 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006629 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006630 return true;
6631 }
6632
6633 return false;
6634}
6635
John McCall3969e302009-12-08 07:46:18 +00006636
John McCallb96ec562009-12-04 22:46:56 +00006637/// Checks that the given nested-name qualifier used in a using decl
6638/// in the current context is appropriately related to the current
6639/// scope. If an error is found, diagnoses it and returns true.
6640bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6641 const CXXScopeSpec &SS,
6642 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006643 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006644
John McCall3969e302009-12-08 07:46:18 +00006645 if (!CurContext->isRecord()) {
6646 // C++03 [namespace.udecl]p3:
6647 // C++0x [namespace.udecl]p8:
6648 // A using-declaration for a class member shall be a member-declaration.
6649
6650 // If we weren't able to compute a valid scope, it must be a
6651 // dependent class scope.
6652 if (!NamedContext || NamedContext->isRecord()) {
6653 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6654 << SS.getRange();
6655 return true;
6656 }
6657
6658 // Otherwise, everything is known to be fine.
6659 return false;
6660 }
6661
6662 // The current scope is a record.
6663
6664 // If the named context is dependent, we can't decide much.
6665 if (!NamedContext) {
6666 // FIXME: in C++0x, we can diagnose if we can prove that the
6667 // nested-name-specifier does not refer to a base class, which is
6668 // still possible in some cases.
6669
6670 // Otherwise we have to conservatively report that things might be
6671 // okay.
6672 return false;
6673 }
6674
6675 if (!NamedContext->isRecord()) {
6676 // Ideally this would point at the last name in the specifier,
6677 // but we don't have that level of source info.
6678 Diag(SS.getRange().getBegin(),
6679 diag::err_using_decl_nested_name_specifier_is_not_class)
6680 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6681 return true;
6682 }
6683
Douglas Gregor7c842292010-12-21 07:41:49 +00006684 if (!NamedContext->isDependentContext() &&
6685 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6686 return true;
6687
John McCall3969e302009-12-08 07:46:18 +00006688 if (getLangOptions().CPlusPlus0x) {
6689 // C++0x [namespace.udecl]p3:
6690 // In a using-declaration used as a member-declaration, the
6691 // nested-name-specifier shall name a base class of the class
6692 // being defined.
6693
6694 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6695 cast<CXXRecordDecl>(NamedContext))) {
6696 if (CurContext == NamedContext) {
6697 Diag(NameLoc,
6698 diag::err_using_decl_nested_name_specifier_is_current_class)
6699 << SS.getRange();
6700 return true;
6701 }
6702
6703 Diag(SS.getRange().getBegin(),
6704 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6705 << (NestedNameSpecifier*) SS.getScopeRep()
6706 << cast<CXXRecordDecl>(CurContext)
6707 << SS.getRange();
6708 return true;
6709 }
6710
6711 return false;
6712 }
6713
6714 // C++03 [namespace.udecl]p4:
6715 // A using-declaration used as a member-declaration shall refer
6716 // to a member of a base class of the class being defined [etc.].
6717
6718 // Salient point: SS doesn't have to name a base class as long as
6719 // lookup only finds members from base classes. Therefore we can
6720 // diagnose here only if we can prove that that can't happen,
6721 // i.e. if the class hierarchies provably don't intersect.
6722
6723 // TODO: it would be nice if "definitely valid" results were cached
6724 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6725 // need to be repeated.
6726
6727 struct UserData {
6728 llvm::DenseSet<const CXXRecordDecl*> Bases;
6729
6730 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6731 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6732 Data->Bases.insert(Base);
6733 return true;
6734 }
6735
6736 bool hasDependentBases(const CXXRecordDecl *Class) {
6737 return !Class->forallBases(collect, this);
6738 }
6739
6740 /// Returns true if the base is dependent or is one of the
6741 /// accumulated base classes.
6742 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6743 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6744 return !Data->Bases.count(Base);
6745 }
6746
6747 bool mightShareBases(const CXXRecordDecl *Class) {
6748 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6749 }
6750 };
6751
6752 UserData Data;
6753
6754 // Returns false if we find a dependent base.
6755 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6756 return false;
6757
6758 // Returns false if the class has a dependent base or if it or one
6759 // of its bases is present in the base set of the current context.
6760 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6761 return false;
6762
6763 Diag(SS.getRange().getBegin(),
6764 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6765 << (NestedNameSpecifier*) SS.getScopeRep()
6766 << cast<CXXRecordDecl>(CurContext)
6767 << SS.getRange();
6768
6769 return true;
John McCallb96ec562009-12-04 22:46:56 +00006770}
6771
Richard Smithdda56e42011-04-15 14:24:37 +00006772Decl *Sema::ActOnAliasDeclaration(Scope *S,
6773 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006774 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006775 SourceLocation UsingLoc,
6776 UnqualifiedId &Name,
6777 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006778 // Skip up to the relevant declaration scope.
6779 while (S->getFlags() & Scope::TemplateParamScope)
6780 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006781 assert((S->getFlags() & Scope::DeclScope) &&
6782 "got alias-declaration outside of declaration scope");
6783
6784 if (Type.isInvalid())
6785 return 0;
6786
6787 bool Invalid = false;
6788 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6789 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006790 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006791
6792 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6793 return 0;
6794
6795 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006796 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006797 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006798 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6799 TInfo->getTypeLoc().getBeginLoc());
6800 }
Richard Smithdda56e42011-04-15 14:24:37 +00006801
6802 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6803 LookupName(Previous, S);
6804
6805 // Warn about shadowing the name of a template parameter.
6806 if (Previous.isSingleResult() &&
6807 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00006808 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00006809 Previous.clear();
6810 }
6811
6812 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6813 "name in alias declaration must be an identifier");
6814 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6815 Name.StartLocation,
6816 Name.Identifier, TInfo);
6817
6818 NewTD->setAccess(AS);
6819
6820 if (Invalid)
6821 NewTD->setInvalidDecl();
6822
Richard Smith3f1b5d02011-05-05 21:57:07 +00006823 CheckTypedefForVariablyModifiedType(S, NewTD);
6824 Invalid |= NewTD->isInvalidDecl();
6825
Richard Smithdda56e42011-04-15 14:24:37 +00006826 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006827
6828 NamedDecl *NewND;
6829 if (TemplateParamLists.size()) {
6830 TypeAliasTemplateDecl *OldDecl = 0;
6831 TemplateParameterList *OldTemplateParams = 0;
6832
6833 if (TemplateParamLists.size() != 1) {
6834 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6835 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6836 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6837 }
6838 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6839
6840 // Only consider previous declarations in the same scope.
6841 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6842 /*ExplicitInstantiationOrSpecialization*/false);
6843 if (!Previous.empty()) {
6844 Redeclaration = true;
6845
6846 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6847 if (!OldDecl && !Invalid) {
6848 Diag(UsingLoc, diag::err_redefinition_different_kind)
6849 << Name.Identifier;
6850
6851 NamedDecl *OldD = Previous.getRepresentativeDecl();
6852 if (OldD->getLocation().isValid())
6853 Diag(OldD->getLocation(), diag::note_previous_definition);
6854
6855 Invalid = true;
6856 }
6857
6858 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6859 if (TemplateParameterListsAreEqual(TemplateParams,
6860 OldDecl->getTemplateParameters(),
6861 /*Complain=*/true,
6862 TPL_TemplateMatch))
6863 OldTemplateParams = OldDecl->getTemplateParameters();
6864 else
6865 Invalid = true;
6866
6867 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6868 if (!Invalid &&
6869 !Context.hasSameType(OldTD->getUnderlyingType(),
6870 NewTD->getUnderlyingType())) {
6871 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6872 // but we can't reasonably accept it.
6873 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6874 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6875 if (OldTD->getLocation().isValid())
6876 Diag(OldTD->getLocation(), diag::note_previous_definition);
6877 Invalid = true;
6878 }
6879 }
6880 }
6881
6882 // Merge any previous default template arguments into our parameters,
6883 // and check the parameter list.
6884 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6885 TPC_TypeAliasTemplate))
6886 return 0;
6887
6888 TypeAliasTemplateDecl *NewDecl =
6889 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6890 Name.Identifier, TemplateParams,
6891 NewTD);
6892
6893 NewDecl->setAccess(AS);
6894
6895 if (Invalid)
6896 NewDecl->setInvalidDecl();
6897 else if (OldDecl)
6898 NewDecl->setPreviousDeclaration(OldDecl);
6899
6900 NewND = NewDecl;
6901 } else {
6902 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6903 NewND = NewTD;
6904 }
Richard Smithdda56e42011-04-15 14:24:37 +00006905
6906 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006907 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006908
Richard Smith3f1b5d02011-05-05 21:57:07 +00006909 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006910}
6911
John McCall48871652010-08-21 09:40:31 +00006912Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006913 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006914 SourceLocation AliasLoc,
6915 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006916 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006917 SourceLocation IdentLoc,
6918 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006919
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006920 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006921 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6922 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006923
Anders Carlssondca83c42009-03-28 06:23:46 +00006924 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006925 NamedDecl *PrevDecl
6926 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6927 ForRedeclaration);
6928 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6929 PrevDecl = 0;
6930
6931 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006932 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006933 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006934 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006935 // FIXME: At some point, we'll want to create the (redundant)
6936 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006937 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006938 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006939 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006940 }
Mike Stump11289f42009-09-09 15:08:12 +00006941
Anders Carlssondca83c42009-03-28 06:23:46 +00006942 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6943 diag::err_redefinition_different_kind;
6944 Diag(AliasLoc, DiagID) << Alias;
6945 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006946 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006947 }
6948
John McCall27b18f82009-11-17 02:14:36 +00006949 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006950 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006951
John McCall9f3059a2009-10-09 21:13:30 +00006952 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006953 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006954 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006955 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006956 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006957 }
Mike Stump11289f42009-09-09 15:08:12 +00006958
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006959 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006960 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006961 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006962 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006963
John McCalld8d0d432010-02-16 06:53:13 +00006964 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006965 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006966}
6967
Douglas Gregora57478e2010-05-01 15:04:51 +00006968namespace {
6969 /// \brief Scoped object used to handle the state changes required in Sema
6970 /// to implicitly define the body of a C++ member function;
6971 class ImplicitlyDefinedFunctionScope {
6972 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006973 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006974
6975 public:
6976 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006977 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006978 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006979 S.PushFunctionScope();
6980 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6981 }
6982
6983 ~ImplicitlyDefinedFunctionScope() {
6984 S.PopExpressionEvaluationContext();
Eli Friedman71c80552012-01-05 03:35:19 +00006985 S.PopFunctionScopeInfo();
Douglas Gregora57478e2010-05-01 15:04:51 +00006986 }
6987 };
6988}
6989
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006990Sema::ImplicitExceptionSpecification
6991Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006992 // C++ [except.spec]p14:
6993 // An implicitly declared special member function (Clause 12) shall have an
6994 // exception-specification. [...]
6995 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006996 if (ClassDecl->isInvalidDecl())
6997 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006998
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006999 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007000 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7001 BEnd = ClassDecl->bases_end();
7002 B != BEnd; ++B) {
7003 if (B->isVirtual()) // Handled below.
7004 continue;
7005
Douglas Gregor9672f922010-07-03 00:47:00 +00007006 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7007 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007008 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7009 // If this is a deleted function, add it anyway. This might be conformant
7010 // with the standard. This might not. I'm not sure. It might not matter.
7011 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007012 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007013 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007014 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007015
7016 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007017 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7018 BEnd = ClassDecl->vbases_end();
7019 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007020 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7021 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007022 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7023 // If this is a deleted function, add it anyway. This might be conformant
7024 // with the standard. This might not. I'm not sure. It might not matter.
7025 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007026 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007027 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007028 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007029
7030 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007031 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7032 FEnd = ClassDecl->field_end();
7033 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00007034 if (F->hasInClassInitializer()) {
7035 if (Expr *E = F->getInClassInitializer())
7036 ExceptSpec.CalledExpr(E);
7037 else if (!F->isInvalidDecl())
7038 ExceptSpec.SetDelayed();
7039 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00007040 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00007041 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7042 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7043 // If this is a deleted function, add it anyway. This might be conformant
7044 // with the standard. This might not. I'm not sure. It might not matter.
7045 // In particular, the problem is that this function never gets called. It
7046 // might just be ill-formed because this function attempts to refer to
7047 // a deleted function here.
7048 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007049 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007050 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007051 }
John McCalldb40c7f2010-12-14 08:05:40 +00007052
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007053 return ExceptSpec;
7054}
7055
7056CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7057 CXXRecordDecl *ClassDecl) {
7058 // C++ [class.ctor]p5:
7059 // A default constructor for a class X is a constructor of class X
7060 // that can be called without an argument. If there is no
7061 // user-declared constructor for class X, a default constructor is
7062 // implicitly declared. An implicitly-declared default constructor
7063 // is an inline public member of its class.
7064 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7065 "Should not build implicit default constructor!");
7066
7067 ImplicitExceptionSpecification Spec =
7068 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7069 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00007070
Douglas Gregor6d880b12010-07-01 22:31:05 +00007071 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007072 CanQualType ClassType
7073 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007074 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007075 DeclarationName Name
7076 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007077 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00007078 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7079 Context, ClassDecl, ClassLoc, NameInfo,
7080 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7081 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7082 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7083 getLangOptions().CPlusPlus0x);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007084 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00007085 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007086 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00007087 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00007088
7089 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00007090 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7091
Douglas Gregor0be31a22010-07-02 17:43:08 +00007092 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00007093 PushOnScopeChains(DefaultCon, S, false);
7094 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007095
Alexis Huntd6da8762011-10-10 06:18:57 +00007096 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007097 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00007098
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007099 return DefaultCon;
7100}
7101
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007102void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7103 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00007104 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007105 !Constructor->doesThisDeclarationHaveABody() &&
7106 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007107 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007108
Anders Carlsson423f5d82010-04-23 16:04:08 +00007109 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00007110 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00007111
Douglas Gregora57478e2010-05-01 15:04:51 +00007112 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007113 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00007114 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007115 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007116 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007117 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00007118 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00007119 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00007120 }
Douglas Gregor73193272010-09-20 16:48:21 +00007121
7122 SourceLocation Loc = Constructor->getLocation();
7123 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7124
7125 Constructor->setUsed();
7126 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007127
7128 if (ASTMutationListener *L = getASTMutationListener()) {
7129 L->CompletedImplicitDefinition(Constructor);
7130 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007131}
7132
Richard Smith938f40b2011-06-11 17:19:42 +00007133/// Get any existing defaulted default constructor for the given class. Do not
7134/// implicitly define one if it does not exist.
7135static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7136 CXXRecordDecl *D) {
7137 ASTContext &Context = Self.Context;
7138 QualType ClassType = Context.getTypeDeclType(D);
7139 DeclarationName ConstructorName
7140 = Context.DeclarationNames.getCXXConstructorName(
7141 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7142
7143 DeclContext::lookup_const_iterator Con, ConEnd;
7144 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7145 Con != ConEnd; ++Con) {
7146 // A function template cannot be defaulted.
7147 if (isa<FunctionTemplateDecl>(*Con))
7148 continue;
7149
7150 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7151 if (Constructor->isDefaultConstructor())
7152 return Constructor->isDefaulted() ? Constructor : 0;
7153 }
7154 return 0;
7155}
7156
7157void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7158 if (!D) return;
7159 AdjustDeclIfTemplate(D);
7160
7161 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7162 CXXConstructorDecl *CtorDecl
7163 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7164
7165 if (!CtorDecl) return;
7166
7167 // Compute the exception specification for the default constructor.
7168 const FunctionProtoType *CtorTy =
7169 CtorDecl->getType()->castAs<FunctionProtoType>();
7170 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7171 ImplicitExceptionSpecification Spec =
7172 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7173 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7174 assert(EPI.ExceptionSpecType != EST_Delayed);
7175
7176 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7177 }
7178
7179 // If the default constructor is explicitly defaulted, checking the exception
7180 // specification is deferred until now.
7181 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7182 !ClassDecl->isDependentType())
7183 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7184}
7185
Sebastian Redl08905022011-02-05 19:23:19 +00007186void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7187 // We start with an initial pass over the base classes to collect those that
7188 // inherit constructors from. If there are none, we can forgo all further
7189 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007190 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00007191 BasesVector BasesToInheritFrom;
7192 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7193 BaseE = ClassDecl->bases_end();
7194 BaseIt != BaseE; ++BaseIt) {
7195 if (BaseIt->getInheritConstructors()) {
7196 QualType Base = BaseIt->getType();
7197 if (Base->isDependentType()) {
7198 // If we inherit constructors from anything that is dependent, just
7199 // abort processing altogether. We'll get another chance for the
7200 // instantiations.
7201 return;
7202 }
7203 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7204 }
7205 }
7206 if (BasesToInheritFrom.empty())
7207 return;
7208
7209 // Now collect the constructors that we already have in the current class.
7210 // Those take precedence over inherited constructors.
7211 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7212 // unless there is a user-declared constructor with the same signature in
7213 // the class where the using-declaration appears.
7214 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7215 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7216 CtorE = ClassDecl->ctor_end();
7217 CtorIt != CtorE; ++CtorIt) {
7218 ExistingConstructors.insert(
7219 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7220 }
7221
7222 Scope *S = getScopeForContext(ClassDecl);
7223 DeclarationName CreatedCtorName =
7224 Context.DeclarationNames.getCXXConstructorName(
7225 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7226
7227 // Now comes the true work.
7228 // First, we keep a map from constructor types to the base that introduced
7229 // them. Needed for finding conflicting constructors. We also keep the
7230 // actually inserted declarations in there, for pretty diagnostics.
7231 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7232 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7233 ConstructorToSourceMap InheritedConstructors;
7234 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7235 BaseE = BasesToInheritFrom.end();
7236 BaseIt != BaseE; ++BaseIt) {
7237 const RecordType *Base = *BaseIt;
7238 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7239 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7240 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7241 CtorE = BaseDecl->ctor_end();
7242 CtorIt != CtorE; ++CtorIt) {
7243 // Find the using declaration for inheriting this base's constructors.
7244 DeclarationName Name =
7245 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7246 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7247 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7248 SourceLocation UsingLoc = UD ? UD->getLocation() :
7249 ClassDecl->getLocation();
7250
7251 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7252 // from the class X named in the using-declaration consists of actual
7253 // constructors and notional constructors that result from the
7254 // transformation of defaulted parameters as follows:
7255 // - all non-template default constructors of X, and
7256 // - for each non-template constructor of X that has at least one
7257 // parameter with a default argument, the set of constructors that
7258 // results from omitting any ellipsis parameter specification and
7259 // successively omitting parameters with a default argument from the
7260 // end of the parameter-type-list.
7261 CXXConstructorDecl *BaseCtor = *CtorIt;
7262 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7263 const FunctionProtoType *BaseCtorType =
7264 BaseCtor->getType()->getAs<FunctionProtoType>();
7265
7266 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7267 maxParams = BaseCtor->getNumParams();
7268 params <= maxParams; ++params) {
7269 // Skip default constructors. They're never inherited.
7270 if (params == 0)
7271 continue;
7272 // Skip copy and move constructors for the same reason.
7273 if (CanBeCopyOrMove && params == 1)
7274 continue;
7275
7276 // Build up a function type for this particular constructor.
7277 // FIXME: The working paper does not consider that the exception spec
7278 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00007279 // source. This code doesn't yet, either. When it does, this code will
7280 // need to be delayed until after exception specifications and in-class
7281 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00007282 const Type *NewCtorType;
7283 if (params == maxParams)
7284 NewCtorType = BaseCtorType;
7285 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007286 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00007287 for (unsigned i = 0; i < params; ++i) {
7288 Args.push_back(BaseCtorType->getArgType(i));
7289 }
7290 FunctionProtoType::ExtProtoInfo ExtInfo =
7291 BaseCtorType->getExtProtoInfo();
7292 ExtInfo.Variadic = false;
7293 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7294 Args.data(), params, ExtInfo)
7295 .getTypePtr();
7296 }
7297 const Type *CanonicalNewCtorType =
7298 Context.getCanonicalType(NewCtorType);
7299
7300 // Now that we have the type, first check if the class already has a
7301 // constructor with this signature.
7302 if (ExistingConstructors.count(CanonicalNewCtorType))
7303 continue;
7304
7305 // Then we check if we have already declared an inherited constructor
7306 // with this signature.
7307 std::pair<ConstructorToSourceMap::iterator, bool> result =
7308 InheritedConstructors.insert(std::make_pair(
7309 CanonicalNewCtorType,
7310 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7311 if (!result.second) {
7312 // Already in the map. If it came from a different class, that's an
7313 // error. Not if it's from the same.
7314 CanQualType PreviousBase = result.first->second.first;
7315 if (CanonicalBase != PreviousBase) {
7316 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7317 const CXXConstructorDecl *PrevBaseCtor =
7318 PrevCtor->getInheritedConstructor();
7319 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7320
7321 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7322 Diag(BaseCtor->getLocation(),
7323 diag::note_using_decl_constructor_conflict_current_ctor);
7324 Diag(PrevBaseCtor->getLocation(),
7325 diag::note_using_decl_constructor_conflict_previous_ctor);
7326 Diag(PrevCtor->getLocation(),
7327 diag::note_using_decl_constructor_conflict_previous_using);
7328 }
7329 continue;
7330 }
7331
7332 // OK, we're there, now add the constructor.
7333 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00007334 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00007335 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7336 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00007337 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7338 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007339 /*ImplicitlyDeclared=*/true,
7340 // FIXME: Due to a defect in the standard, we treat inherited
7341 // constructors as constexpr even if that makes them ill-formed.
7342 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00007343 NewCtor->setAccess(BaseCtor->getAccess());
7344
7345 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007346 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00007347 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007348 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7349 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00007350 /*IdentifierInfo=*/0,
7351 BaseCtorType->getArgType(i),
7352 /*TInfo=*/0, SC_None,
7353 SC_None, /*DefaultArg=*/0));
7354 }
David Blaikie9c70e042011-09-21 18:16:56 +00007355 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00007356 NewCtor->setInheritedConstructor(BaseCtor);
7357
7358 PushOnScopeChains(NewCtor, S, false);
7359 ClassDecl->addDecl(NewCtor);
7360 result.first->second.second = NewCtor;
7361 }
7362 }
7363 }
7364}
7365
Alexis Huntf91729462011-05-12 22:46:25 +00007366Sema::ImplicitExceptionSpecification
7367Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00007368 // C++ [except.spec]p14:
7369 // An implicitly declared special member function (Clause 12) shall have
7370 // an exception-specification.
7371 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007372 if (ClassDecl->isInvalidDecl())
7373 return ExceptSpec;
7374
Douglas Gregorf1203042010-07-01 19:09:28 +00007375 // Direct base-class destructors.
7376 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7377 BEnd = ClassDecl->bases_end();
7378 B != BEnd; ++B) {
7379 if (B->isVirtual()) // Handled below.
7380 continue;
7381
7382 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7383 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007384 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007385 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007386
Douglas Gregorf1203042010-07-01 19:09:28 +00007387 // Virtual base-class destructors.
7388 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7389 BEnd = ClassDecl->vbases_end();
7390 B != BEnd; ++B) {
7391 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7392 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007393 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007394 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007395
Douglas Gregorf1203042010-07-01 19:09:28 +00007396 // Field destructors.
7397 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7398 FEnd = ClassDecl->field_end();
7399 F != FEnd; ++F) {
7400 if (const RecordType *RecordTy
7401 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7402 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007403 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007404 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007405
Alexis Huntf91729462011-05-12 22:46:25 +00007406 return ExceptSpec;
7407}
7408
7409CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7410 // C++ [class.dtor]p2:
7411 // If a class has no user-declared destructor, a destructor is
7412 // declared implicitly. An implicitly-declared destructor is an
7413 // inline public member of its class.
7414
7415 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00007416 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00007417 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7418
Douglas Gregor7454c562010-07-02 20:37:36 +00007419 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00007420 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007421
Douglas Gregorf1203042010-07-01 19:09:28 +00007422 CanQualType ClassType
7423 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007424 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00007425 DeclarationName Name
7426 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007427 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00007428 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007429 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7430 /*isInline=*/true,
7431 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00007432 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00007433 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00007434 Destructor->setImplicit();
7435 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00007436
7437 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00007438 ++ASTContext::NumImplicitDestructorsDeclared;
7439
7440 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007441 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00007442 PushOnScopeChains(Destructor, S, false);
7443 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00007444
7445 // This could be uniqued if it ever proves significant.
7446 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00007447
7448 if (ShouldDeleteDestructor(Destructor))
7449 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00007450
7451 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00007452
Douglas Gregorf1203042010-07-01 19:09:28 +00007453 return Destructor;
7454}
7455
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007456void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00007457 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007458 assert((Destructor->isDefaulted() &&
7459 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007460 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00007461 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007462 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007463
Douglas Gregor54818f02010-05-12 16:39:35 +00007464 if (Destructor->isInvalidDecl())
7465 return;
7466
Douglas Gregora57478e2010-05-01 15:04:51 +00007467 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007468
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007469 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00007470 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7471 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00007472
Douglas Gregor54818f02010-05-12 16:39:35 +00007473 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007474 Diag(CurrentLocation, diag::note_member_synthesized_at)
7475 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7476
7477 Destructor->setInvalidDecl();
7478 return;
7479 }
7480
Douglas Gregor73193272010-09-20 16:48:21 +00007481 SourceLocation Loc = Destructor->getLocation();
7482 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00007483 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007484 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007485 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007486
7487 if (ASTMutationListener *L = getASTMutationListener()) {
7488 L->CompletedImplicitDefinition(Destructor);
7489 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007490}
7491
Sebastian Redl623ea822011-05-19 05:13:44 +00007492void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7493 CXXDestructorDecl *destructor) {
7494 // C++11 [class.dtor]p3:
7495 // A declaration of a destructor that does not have an exception-
7496 // specification is implicitly considered to have the same exception-
7497 // specification as an implicit declaration.
7498 const FunctionProtoType *dtorType = destructor->getType()->
7499 getAs<FunctionProtoType>();
7500 if (dtorType->hasExceptionSpec())
7501 return;
7502
7503 ImplicitExceptionSpecification exceptSpec =
7504 ComputeDefaultedDtorExceptionSpec(classDecl);
7505
Chandler Carruth9a797572011-09-20 04:55:26 +00007506 // Replace the destructor's type, building off the existing one. Fortunately,
7507 // the only thing of interest in the destructor type is its extended info.
7508 // The return and arguments are fixed.
7509 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00007510 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7511 epi.NumExceptions = exceptSpec.size();
7512 epi.Exceptions = exceptSpec.data();
7513 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7514
7515 destructor->setType(ty);
7516
7517 // FIXME: If the destructor has a body that could throw, and the newly created
7518 // spec doesn't allow exceptions, we should emit a warning, because this
7519 // change in behavior can break conforming C++03 programs at runtime.
7520 // However, we don't have a body yet, so it needs to be done somewhere else.
7521}
7522
Sebastian Redl22653ba2011-08-30 19:58:05 +00007523/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00007524/// \c To.
7525///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007526/// This routine is used to copy/move the members of a class with an
7527/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00007528/// copied are arrays, this routine builds for loops to copy them.
7529///
7530/// \param S The Sema object used for type-checking.
7531///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007532/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007533///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007534/// \param T The type of the expressions being copied/moved. Both expressions
7535/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007536///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007537/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007538///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007539/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007540///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007541/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007542/// Otherwise, it's a non-static member subobject.
7543///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007544/// \param Copying Whether we're copying or moving.
7545///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007546/// \param Depth Internal parameter recording the depth of the recursion.
7547///
7548/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007549static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007550BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007551 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007552 bool CopyingBaseSubobject, bool Copying,
7553 unsigned Depth = 0) {
7554 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007555 // Each subobject is assigned in the manner appropriate to its type:
7556 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007557 // - if the subobject is of class type, as if by a call to operator= with
7558 // the subobject as the object expression and the corresponding
7559 // subobject of x as a single function argument (as if by explicit
7560 // qualification; that is, ignoring any possible virtual overriding
7561 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007562 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7563 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7564
7565 // Look for operator=.
7566 DeclarationName Name
7567 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7568 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7569 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7570
Sebastian Redl22653ba2011-08-30 19:58:05 +00007571 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007572 LookupResult::Filter F = OpLookup.makeFilter();
7573 while (F.hasNext()) {
7574 NamedDecl *D = F.next();
7575 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007576 if (Copying ? Method->isCopyAssignmentOperator() :
7577 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007578 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007579
Douglas Gregorb139cd52010-05-01 20:49:11 +00007580 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007581 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007582 F.done();
7583
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007584 // Suppress the protected check (C++ [class.protected]) for each of the
7585 // assignment operators we found. This strange dance is required when
7586 // we're assigning via a base classes's copy-assignment operator. To
7587 // ensure that we're getting the right base class subobject (without
7588 // ambiguities), we need to cast "this" to that subobject type; to
7589 // ensure that we don't go through the virtual call mechanism, we need
7590 // to qualify the operator= name with the base class (see below). However,
7591 // this means that if the base class has a protected copy assignment
7592 // operator, the protected member access check will fail. So, we
7593 // rewrite "protected" access to "public" access in this case, since we
7594 // know by construction that we're calling from a derived class.
7595 if (CopyingBaseSubobject) {
7596 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7597 L != LEnd; ++L) {
7598 if (L.getAccess() == AS_protected)
7599 L.setAccess(AS_public);
7600 }
7601 }
7602
Douglas Gregorb139cd52010-05-01 20:49:11 +00007603 // Create the nested-name-specifier that will be used to qualify the
7604 // reference to operator=; this is required to suppress the virtual
7605 // call mechanism.
7606 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00007607 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregor869ad452011-02-24 17:54:50 +00007608 SS.MakeTrivial(S.Context,
7609 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00007610 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00007611 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007612
7613 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007614 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007615 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00007616 /*TemplateKWLoc=*/SourceLocation(),
7617 /*FirstQualifierInScope=*/0,
7618 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007619 /*TemplateArgs=*/0,
7620 /*SuppressQualifierCheck=*/true);
7621 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007622 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007623
7624 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007625
John McCalldadc5752010-08-24 06:29:42 +00007626 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007627 OpEqualRef.takeAs<Expr>(),
7628 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007629 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007630 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007631
7632 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007633 }
John McCallab8c2732010-03-16 06:11:48 +00007634
Douglas Gregorb139cd52010-05-01 20:49:11 +00007635 // - if the subobject is of scalar type, the built-in assignment
7636 // operator is used.
7637 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7638 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007639 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007640 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007641 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007642
7643 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007644 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007645
7646 // - if the subobject is an array, each element is assigned, in the
7647 // manner appropriate to the element type;
7648
7649 // Construct a loop over the array bounds, e.g.,
7650 //
7651 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7652 //
7653 // that will copy each of the array elements.
7654 QualType SizeType = S.Context.getSizeType();
7655
7656 // Create the iteration variable.
7657 IdentifierInfo *IterationVarName = 0;
7658 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007659 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007660 llvm::raw_svector_ostream OS(Str);
7661 OS << "__i" << Depth;
7662 IterationVarName = &S.Context.Idents.get(OS.str());
7663 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007664 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007665 IterationVarName, SizeType,
7666 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007667 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007668
7669 // Initialize the iteration variable to zero.
7670 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007671 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007672
7673 // Create a reference to the iteration variable; we'll use this several
7674 // times throughout.
7675 Expr *IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00007676 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007677 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00007678 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7679 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7680
Douglas Gregorb139cd52010-05-01 20:49:11 +00007681 // Create the DeclStmt that holds the iteration variable.
7682 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7683
7684 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007685 llvm::APInt Upper
7686 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007687 Expr *Comparison
Eli Friedman844f9452012-01-23 02:35:22 +00007688 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCall7decc9e2010-11-18 06:31:45 +00007689 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7690 BO_NE, S.Context.BoolTy,
7691 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007692
7693 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007694 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007695 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7696 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007697
7698 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007699 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007700 IterationVarRefRVal,
7701 Loc));
John McCallb268a282010-08-23 23:25:46 +00007702 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007703 IterationVarRefRVal,
7704 Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007705 if (!Copying) // Cast to rvalue
7706 From = CastForMoving(S, From);
7707
7708 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007709 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7710 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007711 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007712 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007713 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007714
7715 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007716 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007717 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007718 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007719 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007720}
7721
Alexis Hunt119f3652011-05-14 05:23:20 +00007722std::pair<Sema::ImplicitExceptionSpecification, bool>
7723Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7724 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007725 if (ClassDecl->isInvalidDecl())
7726 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7727
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007728 // C++ [class.copy]p10:
7729 // If the class definition does not explicitly declare a copy
7730 // assignment operator, one is declared implicitly.
7731 // The implicitly-defined copy assignment operator for a class X
7732 // will have the form
7733 //
7734 // X& X::operator=(const X&)
7735 //
7736 // if
7737 bool HasConstCopyAssignment = true;
7738
7739 // -- each direct base class B of X has a copy assignment operator
7740 // whose parameter is of type const B&, const volatile B& or B,
7741 // and
7742 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7743 BaseEnd = ClassDecl->bases_end();
7744 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007745 // We'll handle this below
7746 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7747 continue;
7748
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007749 assert(!Base->getType()->isDependentType() &&
7750 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007751 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7752 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7753 &HasConstCopyAssignment);
7754 }
7755
Richard Smith0bf8a4922011-10-18 20:49:44 +00007756 // In C++11, the above citation has "or virtual" added
Alexis Hunt491ec602011-06-21 23:42:56 +00007757 if (LangOpts.CPlusPlus0x) {
7758 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7759 BaseEnd = ClassDecl->vbases_end();
7760 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7761 assert(!Base->getType()->isDependentType() &&
7762 "Cannot generate implicit members for class with dependent bases.");
7763 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7764 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7765 &HasConstCopyAssignment);
7766 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007767 }
7768
7769 // -- for all the nonstatic data members of X that are of a class
7770 // type M (or array thereof), each such class type has a copy
7771 // assignment operator whose parameter is of type const M&,
7772 // const volatile M& or M.
7773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7774 FieldEnd = ClassDecl->field_end();
7775 HasConstCopyAssignment && Field != FieldEnd;
7776 ++Field) {
7777 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007778 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7779 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7780 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007781 }
7782 }
7783
7784 // Otherwise, the implicitly declared copy assignment operator will
7785 // have the form
7786 //
7787 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007788
Douglas Gregor68e11362010-07-01 17:48:08 +00007789 // C++ [except.spec]p14:
7790 // An implicitly declared special member function (Clause 12) shall have an
7791 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007792
7793 // It is unspecified whether or not an implicit copy assignment operator
7794 // attempts to deduplicate calls to assignment operators of virtual bases are
7795 // made. As such, this exception specification is effectively unspecified.
7796 // Based on a similar decision made for constness in C++0x, we're erring on
7797 // the side of assuming such calls to be made regardless of whether they
7798 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007799 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007800 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007801 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7802 BaseEnd = ClassDecl->bases_end();
7803 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007804 if (Base->isVirtual())
7805 continue;
7806
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007807 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007808 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007809 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7810 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007811 ExceptSpec.CalledDecl(CopyAssign);
7812 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007813
7814 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7815 BaseEnd = ClassDecl->vbases_end();
7816 Base != BaseEnd; ++Base) {
7817 CXXRecordDecl *BaseClassDecl
7818 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7819 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7820 ArgQuals, false, 0))
7821 ExceptSpec.CalledDecl(CopyAssign);
7822 }
7823
Douglas Gregor68e11362010-07-01 17:48:08 +00007824 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7825 FieldEnd = ClassDecl->field_end();
7826 Field != FieldEnd;
7827 ++Field) {
7828 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007829 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7830 if (CXXMethodDecl *CopyAssign =
7831 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7832 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007833 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007834 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007835
Alexis Hunt119f3652011-05-14 05:23:20 +00007836 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7837}
7838
7839CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7840 // Note: The following rules are largely analoguous to the copy
7841 // constructor rules. Note that virtual bases are not taken into account
7842 // for determining the argument type of the operator. Note also that
7843 // operators taking an object instead of a reference are allowed.
7844
7845 ImplicitExceptionSpecification Spec(Context);
7846 bool Const;
7847 llvm::tie(Spec, Const) =
7848 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7849
7850 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7851 QualType RetType = Context.getLValueReferenceType(ArgType);
7852 if (Const)
7853 ArgType = ArgType.withConst();
7854 ArgType = Context.getLValueReferenceType(ArgType);
7855
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007856 // An implicitly-declared copy assignment operator is an inline public
7857 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007858 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007859 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007860 SourceLocation ClassLoc = ClassDecl->getLocation();
7861 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007862 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007863 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007864 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007865 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007866 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007867 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007868 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007869 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007870 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007871 CopyAssignment->setImplicit();
7872 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007873
7874 // Add the parameter to the operator.
7875 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007876 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007877 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007878 SC_None,
7879 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007880 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007881
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007882 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007883 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007884
Douglas Gregor0be31a22010-07-02 17:43:08 +00007885 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007886 PushOnScopeChains(CopyAssignment, S, false);
7887 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007888
Nico Weber94e746d2012-01-23 03:19:29 +00007889 // C++0x [class.copy]p19:
7890 // .... If the class definition does not explicitly declare a copy
7891 // assignment operator, there is no user-declared move constructor, and
7892 // there is no user-declared move assignment operator, a copy assignment
7893 // operator is implicitly declared as defaulted.
7894 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber323076f2012-01-23 04:01:33 +00007895 !getLangOptions().MicrosoftMode) ||
7896 ClassDecl->hasUserDeclaredMoveAssignment() ||
Alexis Huntd74c85f2011-06-22 01:05:13 +00007897 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007898 CopyAssignment->setDeletedAsWritten();
7899
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007900 AddOverriddenMethods(ClassDecl, CopyAssignment);
7901 return CopyAssignment;
7902}
7903
Douglas Gregorb139cd52010-05-01 20:49:11 +00007904void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7905 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007906 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007907 CopyAssignOperator->isOverloadedOperator() &&
7908 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007909 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007910 "DefineImplicitCopyAssignment called for wrong function");
7911
7912 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7913
7914 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7915 CopyAssignOperator->setInvalidDecl();
7916 return;
7917 }
7918
7919 CopyAssignOperator->setUsed();
7920
7921 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007922 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007923
7924 // C++0x [class.copy]p30:
7925 // The implicitly-defined or explicitly-defaulted copy assignment operator
7926 // for a non-union class X performs memberwise copy assignment of its
7927 // subobjects. The direct base classes of X are assigned first, in the
7928 // order of their declaration in the base-specifier-list, and then the
7929 // immediate non-static data members of X are assigned, in the order in
7930 // which they were declared in the class definition.
7931
7932 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007933 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007934
7935 // The parameter for the "other" object, which we are copying from.
7936 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7937 Qualifiers OtherQuals = Other->getType().getQualifiers();
7938 QualType OtherRefType = Other->getType();
7939 if (const LValueReferenceType *OtherRef
7940 = OtherRefType->getAs<LValueReferenceType>()) {
7941 OtherRefType = OtherRef->getPointeeType();
7942 OtherQuals = OtherRefType.getQualifiers();
7943 }
7944
7945 // Our location for everything implicitly-generated.
7946 SourceLocation Loc = CopyAssignOperator->getLocation();
7947
7948 // Construct a reference to the "other" object. We'll be using this
7949 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007950 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007951 assert(OtherRef && "Reference to parameter cannot fail!");
7952
7953 // Construct the "this" pointer. We'll be using this throughout the generated
7954 // ASTs.
7955 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7956 assert(This && "Reference to this cannot fail!");
7957
7958 // Assign base classes.
7959 bool Invalid = false;
7960 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7961 E = ClassDecl->bases_end(); Base != E; ++Base) {
7962 // Form the assignment:
7963 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7964 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007965 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007966 Invalid = true;
7967 continue;
7968 }
7969
John McCallcf142162010-08-07 06:22:56 +00007970 CXXCastPath BasePath;
7971 BasePath.push_back(Base);
7972
Douglas Gregorb139cd52010-05-01 20:49:11 +00007973 // Construct the "from" expression, which is an implicit cast to the
7974 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007975 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007976 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7977 CK_UncheckedDerivedToBase,
7978 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007979
7980 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007981 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007982
7983 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007984 To = ImpCastExprToType(To.take(),
7985 Context.getCVRQualifiedType(BaseType,
7986 CopyAssignOperator->getTypeQualifiers()),
7987 CK_UncheckedDerivedToBase,
7988 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007989
7990 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007991 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007992 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007993 /*CopyingBaseSubobject=*/true,
7994 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007995 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007996 Diag(CurrentLocation, diag::note_member_synthesized_at)
7997 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7998 CopyAssignOperator->setInvalidDecl();
7999 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008000 }
8001
8002 // Success! Record the copy.
8003 Statements.push_back(Copy.takeAs<Expr>());
8004 }
8005
8006 // \brief Reference to the __builtin_memcpy function.
8007 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008008 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008009 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008010
8011 // Assign non-static members.
8012 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8013 FieldEnd = ClassDecl->field_end();
8014 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008015 if (Field->isUnnamedBitfield())
8016 continue;
8017
Douglas Gregorb139cd52010-05-01 20:49:11 +00008018 // Check for members of reference type; we can't copy those.
8019 if (Field->getType()->isReferenceType()) {
8020 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8021 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8022 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008023 Diag(CurrentLocation, diag::note_member_synthesized_at)
8024 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008025 Invalid = true;
8026 continue;
8027 }
8028
8029 // Check for members of const-qualified, non-class type.
8030 QualType BaseType = Context.getBaseElementType(Field->getType());
8031 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8032 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8033 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8034 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008035 Diag(CurrentLocation, diag::note_member_synthesized_at)
8036 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008037 Invalid = true;
8038 continue;
8039 }
John McCall1b1a1db2011-06-17 00:18:42 +00008040
8041 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008042 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8043 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008044
8045 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008046 if (FieldType->isIncompleteArrayType()) {
8047 assert(ClassDecl->hasFlexibleArrayMember() &&
8048 "Incomplete array type is not valid");
8049 continue;
8050 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008051
8052 // Build references to the field in the object we're copying from and to.
8053 CXXScopeSpec SS; // Intentionally empty
8054 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8055 LookupMemberName);
8056 MemberLookup.addDecl(*Field);
8057 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00008058 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00008059 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008060 SS, SourceLocation(), 0,
8061 MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00008062 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00008063 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008064 SS, SourceLocation(), 0,
8065 MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008066 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8067 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8068
8069 // If the field should be copied with __builtin_memcpy rather than via
8070 // explicit assignments, do so. This optimization only applies for arrays
8071 // of scalars and arrays of class type with trivial copy-assignment
8072 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00008073 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00008074 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008075 // Compute the size of the memory buffer to be copied.
8076 QualType SizeType = Context.getSizeType();
8077 llvm::APInt Size(Context.getTypeSize(SizeType),
8078 Context.getTypeSizeInChars(BaseType).getQuantity());
8079 for (const ConstantArrayType *Array
8080 = Context.getAsConstantArrayType(FieldType);
8081 Array;
8082 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00008083 llvm::APInt ArraySize
8084 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008085 Size *= ArraySize;
8086 }
8087
8088 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00008089 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8090 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008091
8092 bool NeedsCollectableMemCpy =
8093 (BaseType->isRecordType() &&
8094 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8095
8096 if (NeedsCollectableMemCpy) {
8097 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008098 // Create a reference to the __builtin_objc_memmove_collectable function.
8099 LookupResult R(*this,
8100 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008101 Loc, LookupOrdinaryName);
8102 LookupName(R, TUScope, true);
8103
8104 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8105 if (!CollectableMemCpy) {
8106 // Something went horribly wrong earlier, and we will have
8107 // complained about it.
8108 Invalid = true;
8109 continue;
8110 }
8111
8112 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8113 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008114 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008115 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8116 }
8117 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008118 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008119 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008120 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8121 LookupOrdinaryName);
8122 LookupName(R, TUScope, true);
8123
8124 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8125 if (!BuiltinMemCpy) {
8126 // Something went horribly wrong earlier, and we will have complained
8127 // about it.
8128 Invalid = true;
8129 continue;
8130 }
8131
8132 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8133 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008134 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008135 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8136 }
8137
John McCall37ad5512010-08-23 06:44:23 +00008138 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008139 CallArgs.push_back(To.takeAs<Expr>());
8140 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008141 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00008142 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008143 if (NeedsCollectableMemCpy)
8144 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008145 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008146 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008147 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008148 else
8149 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008150 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008151 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008152 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008153
Douglas Gregorb139cd52010-05-01 20:49:11 +00008154 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8155 Statements.push_back(Call.takeAs<Expr>());
8156 continue;
8157 }
8158
8159 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00008160 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008161 To.get(), From.get(),
8162 /*CopyingBaseSubobject=*/false,
8163 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008164 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008165 Diag(CurrentLocation, diag::note_member_synthesized_at)
8166 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8167 CopyAssignOperator->setInvalidDecl();
8168 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008169 }
8170
8171 // Success! Record the copy.
8172 Statements.push_back(Copy.takeAs<Stmt>());
8173 }
8174
8175 if (!Invalid) {
8176 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00008177 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008178
John McCalldadc5752010-08-24 06:29:42 +00008179 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008180 if (Return.isInvalid())
8181 Invalid = true;
8182 else {
8183 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00008184
8185 if (Trap.hasErrorOccurred()) {
8186 Diag(CurrentLocation, diag::note_member_synthesized_at)
8187 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8188 Invalid = true;
8189 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008190 }
8191 }
8192
8193 if (Invalid) {
8194 CopyAssignOperator->setInvalidDecl();
8195 return;
8196 }
8197
John McCalldadc5752010-08-24 06:29:42 +00008198 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00008199 /*isStmtExpr=*/false);
8200 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8201 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00008202
8203 if (ASTMutationListener *L = getASTMutationListener()) {
8204 L->CompletedImplicitDefinition(CopyAssignOperator);
8205 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008206}
8207
Sebastian Redl22653ba2011-08-30 19:58:05 +00008208Sema::ImplicitExceptionSpecification
8209Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8210 ImplicitExceptionSpecification ExceptSpec(Context);
8211
8212 if (ClassDecl->isInvalidDecl())
8213 return ExceptSpec;
8214
8215 // C++0x [except.spec]p14:
8216 // An implicitly declared special member function (Clause 12) shall have an
8217 // exception-specification. [...]
8218
8219 // It is unspecified whether or not an implicit move assignment operator
8220 // attempts to deduplicate calls to assignment operators of virtual bases are
8221 // made. As such, this exception specification is effectively unspecified.
8222 // Based on a similar decision made for constness in C++0x, we're erring on
8223 // the side of assuming such calls to be made regardless of whether they
8224 // actually happen.
8225 // Note that a move constructor is not implicitly declared when there are
8226 // virtual bases, but it can still be user-declared and explicitly defaulted.
8227 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8228 BaseEnd = ClassDecl->bases_end();
8229 Base != BaseEnd; ++Base) {
8230 if (Base->isVirtual())
8231 continue;
8232
8233 CXXRecordDecl *BaseClassDecl
8234 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8235 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8236 false, 0))
8237 ExceptSpec.CalledDecl(MoveAssign);
8238 }
8239
8240 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8241 BaseEnd = ClassDecl->vbases_end();
8242 Base != BaseEnd; ++Base) {
8243 CXXRecordDecl *BaseClassDecl
8244 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8245 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8246 false, 0))
8247 ExceptSpec.CalledDecl(MoveAssign);
8248 }
8249
8250 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8251 FieldEnd = ClassDecl->field_end();
8252 Field != FieldEnd;
8253 ++Field) {
8254 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8255 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8256 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8257 false, 0))
8258 ExceptSpec.CalledDecl(MoveAssign);
8259 }
8260 }
8261
8262 return ExceptSpec;
8263}
8264
8265CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8266 // Note: The following rules are largely analoguous to the move
8267 // constructor rules.
8268
8269 ImplicitExceptionSpecification Spec(
8270 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8271
8272 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8273 QualType RetType = Context.getLValueReferenceType(ArgType);
8274 ArgType = Context.getRValueReferenceType(ArgType);
8275
8276 // An implicitly-declared move assignment operator is an inline public
8277 // member of its class.
8278 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8279 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8280 SourceLocation ClassLoc = ClassDecl->getLocation();
8281 DeclarationNameInfo NameInfo(Name, ClassLoc);
8282 CXXMethodDecl *MoveAssignment
8283 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8284 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8285 /*TInfo=*/0, /*isStatic=*/false,
8286 /*StorageClassAsWritten=*/SC_None,
8287 /*isInline=*/true,
8288 /*isConstexpr=*/false,
8289 SourceLocation());
8290 MoveAssignment->setAccess(AS_public);
8291 MoveAssignment->setDefaulted();
8292 MoveAssignment->setImplicit();
8293 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8294
8295 // Add the parameter to the operator.
8296 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8297 ClassLoc, ClassLoc, /*Id=*/0,
8298 ArgType, /*TInfo=*/0,
8299 SC_None,
8300 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008301 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008302
8303 // Note that we have added this copy-assignment operator.
8304 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8305
8306 // C++0x [class.copy]p9:
8307 // If the definition of a class X does not explicitly declare a move
8308 // assignment operator, one will be implicitly declared as defaulted if and
8309 // only if:
8310 // [...]
8311 // - the move assignment operator would not be implicitly defined as
8312 // deleted.
8313 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8314 // Cache this result so that we don't try to generate this over and over
8315 // on every lookup, leaking memory and wasting time.
8316 ClassDecl->setFailedImplicitMoveAssignment();
8317 return 0;
8318 }
8319
8320 if (Scope *S = getScopeForContext(ClassDecl))
8321 PushOnScopeChains(MoveAssignment, S, false);
8322 ClassDecl->addDecl(MoveAssignment);
8323
8324 AddOverriddenMethods(ClassDecl, MoveAssignment);
8325 return MoveAssignment;
8326}
8327
8328void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8329 CXXMethodDecl *MoveAssignOperator) {
8330 assert((MoveAssignOperator->isDefaulted() &&
8331 MoveAssignOperator->isOverloadedOperator() &&
8332 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8333 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8334 "DefineImplicitMoveAssignment called for wrong function");
8335
8336 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8337
8338 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8339 MoveAssignOperator->setInvalidDecl();
8340 return;
8341 }
8342
8343 MoveAssignOperator->setUsed();
8344
8345 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8346 DiagnosticErrorTrap Trap(Diags);
8347
8348 // C++0x [class.copy]p28:
8349 // The implicitly-defined or move assignment operator for a non-union class
8350 // X performs memberwise move assignment of its subobjects. The direct base
8351 // classes of X are assigned first, in the order of their declaration in the
8352 // base-specifier-list, and then the immediate non-static data members of X
8353 // are assigned, in the order in which they were declared in the class
8354 // definition.
8355
8356 // The statements that form the synthesized function body.
8357 ASTOwningVector<Stmt*> Statements(*this);
8358
8359 // The parameter for the "other" object, which we are move from.
8360 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8361 QualType OtherRefType = Other->getType()->
8362 getAs<RValueReferenceType>()->getPointeeType();
8363 assert(OtherRefType.getQualifiers() == 0 &&
8364 "Bad argument type of defaulted move assignment");
8365
8366 // Our location for everything implicitly-generated.
8367 SourceLocation Loc = MoveAssignOperator->getLocation();
8368
8369 // Construct a reference to the "other" object. We'll be using this
8370 // throughout the generated ASTs.
8371 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8372 assert(OtherRef && "Reference to parameter cannot fail!");
8373 // Cast to rvalue.
8374 OtherRef = CastForMoving(*this, OtherRef);
8375
8376 // Construct the "this" pointer. We'll be using this throughout the generated
8377 // ASTs.
8378 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8379 assert(This && "Reference to this cannot fail!");
8380
8381 // Assign base classes.
8382 bool Invalid = false;
8383 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8384 E = ClassDecl->bases_end(); Base != E; ++Base) {
8385 // Form the assignment:
8386 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8387 QualType BaseType = Base->getType().getUnqualifiedType();
8388 if (!BaseType->isRecordType()) {
8389 Invalid = true;
8390 continue;
8391 }
8392
8393 CXXCastPath BasePath;
8394 BasePath.push_back(Base);
8395
8396 // Construct the "from" expression, which is an implicit cast to the
8397 // appropriately-qualified base type.
8398 Expr *From = OtherRef;
8399 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00008400 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00008401
8402 // Dereference "this".
8403 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8404
8405 // Implicitly cast "this" to the appropriately-qualified base type.
8406 To = ImpCastExprToType(To.take(),
8407 Context.getCVRQualifiedType(BaseType,
8408 MoveAssignOperator->getTypeQualifiers()),
8409 CK_UncheckedDerivedToBase,
8410 VK_LValue, &BasePath);
8411
8412 // Build the move.
8413 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8414 To.get(), From,
8415 /*CopyingBaseSubobject=*/true,
8416 /*Copying=*/false);
8417 if (Move.isInvalid()) {
8418 Diag(CurrentLocation, diag::note_member_synthesized_at)
8419 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8420 MoveAssignOperator->setInvalidDecl();
8421 return;
8422 }
8423
8424 // Success! Record the move.
8425 Statements.push_back(Move.takeAs<Expr>());
8426 }
8427
8428 // \brief Reference to the __builtin_memcpy function.
8429 Expr *BuiltinMemCpyRef = 0;
8430 // \brief Reference to the __builtin_objc_memmove_collectable function.
8431 Expr *CollectableMemCpyRef = 0;
8432
8433 // Assign non-static members.
8434 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8435 FieldEnd = ClassDecl->field_end();
8436 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008437 if (Field->isUnnamedBitfield())
8438 continue;
8439
Sebastian Redl22653ba2011-08-30 19:58:05 +00008440 // Check for members of reference type; we can't move those.
8441 if (Field->getType()->isReferenceType()) {
8442 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8443 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8444 Diag(Field->getLocation(), diag::note_declared_at);
8445 Diag(CurrentLocation, diag::note_member_synthesized_at)
8446 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8447 Invalid = true;
8448 continue;
8449 }
8450
8451 // Check for members of const-qualified, non-class type.
8452 QualType BaseType = Context.getBaseElementType(Field->getType());
8453 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8454 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8455 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8456 Diag(Field->getLocation(), diag::note_declared_at);
8457 Diag(CurrentLocation, diag::note_member_synthesized_at)
8458 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8459 Invalid = true;
8460 continue;
8461 }
8462
8463 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008464 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8465 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00008466
8467 QualType FieldType = Field->getType().getNonReferenceType();
8468 if (FieldType->isIncompleteArrayType()) {
8469 assert(ClassDecl->hasFlexibleArrayMember() &&
8470 "Incomplete array type is not valid");
8471 continue;
8472 }
8473
8474 // Build references to the field in the object we're copying from and to.
8475 CXXScopeSpec SS; // Intentionally empty
8476 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8477 LookupMemberName);
8478 MemberLookup.addDecl(*Field);
8479 MemberLookup.resolveKind();
8480 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8481 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008482 SS, SourceLocation(), 0,
8483 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008484 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8485 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008486 SS, SourceLocation(), 0,
8487 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008488 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8489 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8490
8491 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8492 "Member reference with rvalue base must be rvalue except for reference "
8493 "members, which aren't allowed for move assignment.");
8494
8495 // If the field should be copied with __builtin_memcpy rather than via
8496 // explicit assignments, do so. This optimization only applies for arrays
8497 // of scalars and arrays of class type with trivial move-assignment
8498 // operators.
8499 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8500 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8501 // Compute the size of the memory buffer to be copied.
8502 QualType SizeType = Context.getSizeType();
8503 llvm::APInt Size(Context.getTypeSize(SizeType),
8504 Context.getTypeSizeInChars(BaseType).getQuantity());
8505 for (const ConstantArrayType *Array
8506 = Context.getAsConstantArrayType(FieldType);
8507 Array;
8508 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8509 llvm::APInt ArraySize
8510 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8511 Size *= ArraySize;
8512 }
8513
Douglas Gregor528499b2011-09-01 02:09:07 +00008514 // Take the address of the field references for "from" and "to". We
8515 // directly construct UnaryOperators here because semantic analysis
8516 // does not permit us to take the address of an xvalue.
8517 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8518 Context.getPointerType(From.get()->getType()),
8519 VK_RValue, OK_Ordinary, Loc);
8520 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8521 Context.getPointerType(To.get()->getType()),
8522 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008523
8524 bool NeedsCollectableMemCpy =
8525 (BaseType->isRecordType() &&
8526 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8527
8528 if (NeedsCollectableMemCpy) {
8529 if (!CollectableMemCpyRef) {
8530 // Create a reference to the __builtin_objc_memmove_collectable function.
8531 LookupResult R(*this,
8532 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8533 Loc, LookupOrdinaryName);
8534 LookupName(R, TUScope, true);
8535
8536 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8537 if (!CollectableMemCpy) {
8538 // Something went horribly wrong earlier, and we will have
8539 // complained about it.
8540 Invalid = true;
8541 continue;
8542 }
8543
8544 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8545 CollectableMemCpy->getType(),
8546 VK_LValue, Loc, 0).take();
8547 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8548 }
8549 }
8550 // Create a reference to the __builtin_memcpy builtin function.
8551 else if (!BuiltinMemCpyRef) {
8552 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8553 LookupOrdinaryName);
8554 LookupName(R, TUScope, true);
8555
8556 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8557 if (!BuiltinMemCpy) {
8558 // Something went horribly wrong earlier, and we will have complained
8559 // about it.
8560 Invalid = true;
8561 continue;
8562 }
8563
8564 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8565 BuiltinMemCpy->getType(),
8566 VK_LValue, Loc, 0).take();
8567 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8568 }
8569
8570 ASTOwningVector<Expr*> CallArgs(*this);
8571 CallArgs.push_back(To.takeAs<Expr>());
8572 CallArgs.push_back(From.takeAs<Expr>());
8573 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8574 ExprResult Call = ExprError();
8575 if (NeedsCollectableMemCpy)
8576 Call = ActOnCallExpr(/*Scope=*/0,
8577 CollectableMemCpyRef,
8578 Loc, move_arg(CallArgs),
8579 Loc);
8580 else
8581 Call = ActOnCallExpr(/*Scope=*/0,
8582 BuiltinMemCpyRef,
8583 Loc, move_arg(CallArgs),
8584 Loc);
8585
8586 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8587 Statements.push_back(Call.takeAs<Expr>());
8588 continue;
8589 }
8590
8591 // Build the move of this field.
8592 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8593 To.get(), From.get(),
8594 /*CopyingBaseSubobject=*/false,
8595 /*Copying=*/false);
8596 if (Move.isInvalid()) {
8597 Diag(CurrentLocation, diag::note_member_synthesized_at)
8598 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8599 MoveAssignOperator->setInvalidDecl();
8600 return;
8601 }
8602
8603 // Success! Record the copy.
8604 Statements.push_back(Move.takeAs<Stmt>());
8605 }
8606
8607 if (!Invalid) {
8608 // Add a "return *this;"
8609 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8610
8611 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8612 if (Return.isInvalid())
8613 Invalid = true;
8614 else {
8615 Statements.push_back(Return.takeAs<Stmt>());
8616
8617 if (Trap.hasErrorOccurred()) {
8618 Diag(CurrentLocation, diag::note_member_synthesized_at)
8619 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8620 Invalid = true;
8621 }
8622 }
8623 }
8624
8625 if (Invalid) {
8626 MoveAssignOperator->setInvalidDecl();
8627 return;
8628 }
8629
8630 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8631 /*isStmtExpr=*/false);
8632 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8633 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8634
8635 if (ASTMutationListener *L = getASTMutationListener()) {
8636 L->CompletedImplicitDefinition(MoveAssignOperator);
8637 }
8638}
8639
Alexis Hunt913820d2011-05-13 06:10:58 +00008640std::pair<Sema::ImplicitExceptionSpecification, bool>
8641Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008642 if (ClassDecl->isInvalidDecl())
8643 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8644
Douglas Gregor54be3392010-07-01 17:57:27 +00008645 // C++ [class.copy]p5:
8646 // The implicitly-declared copy constructor for a class X will
8647 // have the form
8648 //
8649 // X::X(const X&)
8650 //
8651 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008652 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008653 bool HasConstCopyConstructor = true;
8654
8655 // -- each direct or virtual base class B of X has a copy
8656 // constructor whose first parameter is of type const B& or
8657 // const volatile B&, and
8658 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8659 BaseEnd = ClassDecl->bases_end();
8660 HasConstCopyConstructor && Base != BaseEnd;
8661 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008662 // Virtual bases are handled below.
8663 if (Base->isVirtual())
8664 continue;
8665
Douglas Gregora6d69502010-07-02 23:41:54 +00008666 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008667 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008668 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8669 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008670 }
8671
8672 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8673 BaseEnd = ClassDecl->vbases_end();
8674 HasConstCopyConstructor && Base != BaseEnd;
8675 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008676 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008677 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008678 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8679 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008680 }
8681
8682 // -- for all the nonstatic data members of X that are of a
8683 // class type M (or array thereof), each such class type
8684 // has a copy constructor whose first parameter is of type
8685 // const M& or const volatile M&.
8686 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8687 FieldEnd = ClassDecl->field_end();
8688 HasConstCopyConstructor && Field != FieldEnd;
8689 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008690 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008691 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008692 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8693 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008694 }
8695 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008696 // Otherwise, the implicitly declared copy constructor will have
8697 // the form
8698 //
8699 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008700
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008701 // C++ [except.spec]p14:
8702 // An implicitly declared special member function (Clause 12) shall have an
8703 // exception-specification. [...]
8704 ImplicitExceptionSpecification ExceptSpec(Context);
8705 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8706 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8707 BaseEnd = ClassDecl->bases_end();
8708 Base != BaseEnd;
8709 ++Base) {
8710 // Virtual bases are handled below.
8711 if (Base->isVirtual())
8712 continue;
8713
Douglas Gregora6d69502010-07-02 23:41:54 +00008714 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008715 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008716 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008717 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008718 ExceptSpec.CalledDecl(CopyConstructor);
8719 }
8720 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8721 BaseEnd = ClassDecl->vbases_end();
8722 Base != BaseEnd;
8723 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008724 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008725 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008726 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008727 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008728 ExceptSpec.CalledDecl(CopyConstructor);
8729 }
8730 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8731 FieldEnd = ClassDecl->field_end();
8732 Field != FieldEnd;
8733 ++Field) {
8734 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008735 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8736 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008737 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008738 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008739 }
8740 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008741
Alexis Hunt913820d2011-05-13 06:10:58 +00008742 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8743}
8744
8745CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8746 CXXRecordDecl *ClassDecl) {
8747 // C++ [class.copy]p4:
8748 // If the class definition does not explicitly declare a copy
8749 // constructor, one is declared implicitly.
8750
8751 ImplicitExceptionSpecification Spec(Context);
8752 bool Const;
8753 llvm::tie(Spec, Const) =
8754 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8755
8756 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8757 QualType ArgType = ClassType;
8758 if (Const)
8759 ArgType = ArgType.withConst();
8760 ArgType = Context.getLValueReferenceType(ArgType);
8761
8762 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8763
Douglas Gregor54be3392010-07-01 17:57:27 +00008764 DeclarationName Name
8765 = Context.DeclarationNames.getCXXConstructorName(
8766 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008767 SourceLocation ClassLoc = ClassDecl->getLocation();
8768 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008769
8770 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008771 // member of its class.
8772 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8773 Context, ClassDecl, ClassLoc, NameInfo,
8774 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8775 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8776 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8777 getLangOptions().CPlusPlus0x);
Douglas Gregor54be3392010-07-01 17:57:27 +00008778 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008779 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008780 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008781
Douglas Gregora6d69502010-07-02 23:41:54 +00008782 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008783 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8784
Douglas Gregor54be3392010-07-01 17:57:27 +00008785 // Add the parameter to the constructor.
8786 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008787 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008788 /*IdentifierInfo=*/0,
8789 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008790 SC_None,
8791 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008792 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008793
Douglas Gregor0be31a22010-07-02 17:43:08 +00008794 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008795 PushOnScopeChains(CopyConstructor, S, false);
8796 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008797
Nico Weber94e746d2012-01-23 03:19:29 +00008798 // C++11 [class.copy]p8:
8799 // ... If the class definition does not explicitly declare a copy
8800 // constructor, there is no user-declared move constructor, and there is no
8801 // user-declared move assignment operator, a copy constructor is implicitly
8802 // declared as defaulted.
Alexis Huntd74c85f2011-06-22 01:05:13 +00008803 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weber94e746d2012-01-23 03:19:29 +00008804 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber323076f2012-01-23 04:01:33 +00008805 !getLangOptions().MicrosoftMode) ||
Alexis Hunt1bc6f712011-10-11 04:55:36 +00008806 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008807 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008808
8809 return CopyConstructor;
8810}
8811
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008812void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008813 CXXConstructorDecl *CopyConstructor) {
8814 assert((CopyConstructor->isDefaulted() &&
8815 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008816 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008817 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008818
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008819 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008820 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008821
Douglas Gregora57478e2010-05-01 15:04:51 +00008822 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008823 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008824
Alexis Hunt1d792652011-01-08 20:30:50 +00008825 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008826 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008827 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008828 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008829 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008830 } else {
8831 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8832 CopyConstructor->getLocation(),
8833 MultiStmtArg(*this, 0, 0),
8834 /*isStmtExpr=*/false)
8835 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008836 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008837 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008838
8839 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008840 if (ASTMutationListener *L = getASTMutationListener()) {
8841 L->CompletedImplicitDefinition(CopyConstructor);
8842 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008843}
8844
Sebastian Redl22653ba2011-08-30 19:58:05 +00008845Sema::ImplicitExceptionSpecification
8846Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8847 // C++ [except.spec]p14:
8848 // An implicitly declared special member function (Clause 12) shall have an
8849 // exception-specification. [...]
8850 ImplicitExceptionSpecification ExceptSpec(Context);
8851 if (ClassDecl->isInvalidDecl())
8852 return ExceptSpec;
8853
8854 // Direct base-class constructors.
8855 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8856 BEnd = ClassDecl->bases_end();
8857 B != BEnd; ++B) {
8858 if (B->isVirtual()) // Handled below.
8859 continue;
8860
8861 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8862 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8863 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8864 // If this is a deleted function, add it anyway. This might be conformant
8865 // with the standard. This might not. I'm not sure. It might not matter.
8866 if (Constructor)
8867 ExceptSpec.CalledDecl(Constructor);
8868 }
8869 }
8870
8871 // Virtual base-class constructors.
8872 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8873 BEnd = ClassDecl->vbases_end();
8874 B != BEnd; ++B) {
8875 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8876 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8877 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8878 // If this is a deleted function, add it anyway. This might be conformant
8879 // with the standard. This might not. I'm not sure. It might not matter.
8880 if (Constructor)
8881 ExceptSpec.CalledDecl(Constructor);
8882 }
8883 }
8884
8885 // Field constructors.
8886 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8887 FEnd = ClassDecl->field_end();
8888 F != FEnd; ++F) {
Douglas Gregor7db3e952011-11-28 20:03:15 +00008889 if (const RecordType *RecordTy
Sebastian Redl22653ba2011-08-30 19:58:05 +00008890 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8891 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8892 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8893 // If this is a deleted function, add it anyway. This might be conformant
8894 // with the standard. This might not. I'm not sure. It might not matter.
8895 // In particular, the problem is that this function never gets called. It
8896 // might just be ill-formed because this function attempts to refer to
8897 // a deleted function here.
8898 if (Constructor)
8899 ExceptSpec.CalledDecl(Constructor);
8900 }
8901 }
8902
8903 return ExceptSpec;
8904}
8905
8906CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8907 CXXRecordDecl *ClassDecl) {
8908 ImplicitExceptionSpecification Spec(
8909 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8910
8911 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8912 QualType ArgType = Context.getRValueReferenceType(ClassType);
8913
8914 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8915
8916 DeclarationName Name
8917 = Context.DeclarationNames.getCXXConstructorName(
8918 Context.getCanonicalType(ClassType));
8919 SourceLocation ClassLoc = ClassDecl->getLocation();
8920 DeclarationNameInfo NameInfo(Name, ClassLoc);
8921
8922 // C++0x [class.copy]p11:
8923 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008924 // member of its class.
8925 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8926 Context, ClassDecl, ClassLoc, NameInfo,
8927 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8928 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8929 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8930 getLangOptions().CPlusPlus0x);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008931 MoveConstructor->setAccess(AS_public);
8932 MoveConstructor->setDefaulted();
8933 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008934
Sebastian Redl22653ba2011-08-30 19:58:05 +00008935 // Add the parameter to the constructor.
8936 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8937 ClassLoc, ClassLoc,
8938 /*IdentifierInfo=*/0,
8939 ArgType, /*TInfo=*/0,
8940 SC_None,
8941 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008942 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008943
8944 // C++0x [class.copy]p9:
8945 // If the definition of a class X does not explicitly declare a move
8946 // constructor, one will be implicitly declared as defaulted if and only if:
8947 // [...]
8948 // - the move constructor would not be implicitly defined as deleted.
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00008949 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00008950 // Cache this result so that we don't try to generate this over and over
8951 // on every lookup, leaking memory and wasting time.
8952 ClassDecl->setFailedImplicitMoveConstructor();
8953 return 0;
8954 }
8955
8956 // Note that we have declared this constructor.
8957 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8958
8959 if (Scope *S = getScopeForContext(ClassDecl))
8960 PushOnScopeChains(MoveConstructor, S, false);
8961 ClassDecl->addDecl(MoveConstructor);
8962
8963 return MoveConstructor;
8964}
8965
8966void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8967 CXXConstructorDecl *MoveConstructor) {
8968 assert((MoveConstructor->isDefaulted() &&
8969 MoveConstructor->isMoveConstructor() &&
8970 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8971 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8972
8973 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8974 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8975
8976 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8977 DiagnosticErrorTrap Trap(Diags);
8978
8979 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8980 Trap.hasErrorOccurred()) {
8981 Diag(CurrentLocation, diag::note_member_synthesized_at)
8982 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8983 MoveConstructor->setInvalidDecl();
8984 } else {
8985 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8986 MoveConstructor->getLocation(),
8987 MultiStmtArg(*this, 0, 0),
8988 /*isStmtExpr=*/false)
8989 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008990 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008991 }
8992
8993 MoveConstructor->setUsed();
8994
8995 if (ASTMutationListener *L = getASTMutationListener()) {
8996 L->CompletedImplicitDefinition(MoveConstructor);
8997 }
8998}
8999
John McCalldadc5752010-08-24 06:29:42 +00009000ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00009001Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00009002 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00009003 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009004 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009005 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009006 unsigned ConstructKind,
9007 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00009008 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00009009
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009010 // C++0x [class.copy]p34:
9011 // When certain criteria are met, an implementation is allowed to
9012 // omit the copy/move construction of a class object, even if the
9013 // copy/move constructor and/or destructor for the object have
9014 // side effects. [...]
9015 // - when a temporary class object that has not been bound to a
9016 // reference (12.2) would be copied/moved to a class object
9017 // with the same cv-unqualified type, the copy/move operation
9018 // can be omitted by constructing the temporary object
9019 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00009020 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00009021 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009022 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00009023 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00009024 }
Mike Stump11289f42009-09-09 15:08:12 +00009025
9026 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009027 Elidable, move(ExprArgs), HadMultipleCandidates,
9028 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00009029}
9030
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009031/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9032/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00009033ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00009034Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9035 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00009036 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009037 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009038 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009039 unsigned ConstructKind,
9040 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00009041 unsigned NumExprs = ExprArgs.size();
9042 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00009043
Nick Lewyckyd4693212011-03-25 01:44:32 +00009044 for (specific_attr_iterator<NonNullAttr>
9045 i = Constructor->specific_attr_begin<NonNullAttr>(),
9046 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9047 const NonNullAttr *NonNull = *i;
9048 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9049 }
9050
Eli Friedmanfa0df832012-02-02 03:46:19 +00009051 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00009052 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009053 Constructor, Elidable, Exprs, NumExprs,
9054 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009055 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9056 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009057}
9058
Mike Stump11289f42009-09-09 15:08:12 +00009059bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009060 CXXConstructorDecl *Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009061 MultiExprArg Exprs,
9062 bool HadMultipleCandidates) {
Chandler Carruth01718152010-10-25 08:47:36 +00009063 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00009064 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00009065 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009066 move(Exprs), HadMultipleCandidates, false,
9067 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009068 if (TempResult.isInvalid())
9069 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009070
Anders Carlsson6eb55572009-08-25 05:12:04 +00009071 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00009072 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009073 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00009074 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00009075 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00009076
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009077 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00009078}
9079
John McCall03c48482010-02-02 09:10:11 +00009080void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00009081 if (VD->isInvalidDecl()) return;
9082
John McCall03c48482010-02-02 09:10:11 +00009083 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00009084 if (ClassDecl->isInvalidDecl()) return;
9085 if (ClassDecl->hasTrivialDestructor()) return;
9086 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00009087
Chandler Carruth86d17d32011-03-27 21:26:48 +00009088 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009089 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +00009090 CheckDestructorAccess(VD->getLocation(), Destructor,
9091 PDiag(diag::err_access_dtor_var)
9092 << VD->getDeclName()
9093 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00009094
Chandler Carruth86d17d32011-03-27 21:26:48 +00009095 if (!VD->hasGlobalStorage()) return;
9096
9097 // Emit warning for non-trivial dtor in global scope (a real global,
9098 // class-static, function-static).
9099 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9100
9101 // TODO: this should be re-enabled for static locals by !CXAAtExit
9102 if (!VD->isStaticLocal())
9103 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009104}
9105
Mike Stump11289f42009-09-09 15:08:12 +00009106/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009107/// ActOnDeclarator, when a C++ direct initializer is present.
9108/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00009109void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00009110 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009111 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00009112 SourceLocation RParenLoc,
9113 bool TypeMayContainAuto) {
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009114 // If there is no declaration, there was an error parsing it. Just ignore
9115 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00009116 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009117 return;
Mike Stump11289f42009-09-09 15:08:12 +00009118
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009119 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9120 if (!VDecl) {
9121 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9122 RealDecl->setInvalidDecl();
9123 return;
9124 }
9125
Eli Friedmande30e522012-01-05 22:34:08 +00009126 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith30482bc2011-02-20 03:19:35 +00009127 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedmande30e522012-01-05 22:34:08 +00009128 if (Exprs.size() == 0) {
9129 // It isn't possible to write this directly, but it is possible to
9130 // end up in this situation with "auto x(some_pack...);"
9131 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9132 << VDecl->getDeclName() << VDecl->getType()
9133 << VDecl->getSourceRange();
9134 RealDecl->setInvalidDecl();
9135 return;
9136 }
9137
Richard Smith30482bc2011-02-20 03:19:35 +00009138 if (Exprs.size() > 1) {
9139 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9140 diag::err_auto_var_init_multiple_expressions)
9141 << VDecl->getDeclName() << VDecl->getType()
9142 << VDecl->getSourceRange();
9143 RealDecl->setInvalidDecl();
9144 return;
9145 }
9146
9147 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00009148 TypeSourceInfo *DeducedType = 0;
Sebastian Redl09edce02012-01-23 22:09:39 +00009149 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9150 DAR_Failed)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00009151 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smith9647d3c2011-03-17 16:11:59 +00009152 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00009153 RealDecl->setInvalidDecl();
9154 return;
9155 }
Richard Smith9647d3c2011-03-17 16:11:59 +00009156 VDecl->setTypeSourceInfo(DeducedType);
9157 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00009158
John McCall31168b02011-06-15 23:02:42 +00009159 // In ARC, infer lifetime.
9160 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9161 VDecl->setInvalidDecl();
9162
Richard Smith30482bc2011-02-20 03:19:35 +00009163 // If this is a redeclaration, check that the type we just deduced matches
9164 // the previously declared type.
Douglas Gregorec9fd132012-01-14 16:38:05 +00009165 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith30482bc2011-02-20 03:19:35 +00009166 MergeVarDeclTypes(VDecl, Old);
9167 }
9168
Douglas Gregor402250f2009-08-26 21:14:46 +00009169 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009170 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009171 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9172 //
9173 // Clients that want to distinguish between the two forms, can check for
9174 // direct initializer using VarDecl::hasCXXDirectInitializer().
9175 // A major benefit is that clients that don't particularly care about which
9176 // exactly form was it (like the CodeGen) can handle both cases without
9177 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009178
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009179 // C++ 8.5p11:
9180 // The form of initialization (using parentheses or '=') is generally
9181 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009182 // class type.
9183
Douglas Gregor50dc2192010-02-11 22:55:30 +00009184 if (!VDecl->getType()->isDependentType() &&
Douglas Gregorb06fa542011-10-10 16:05:18 +00009185 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor50dc2192010-02-11 22:55:30 +00009186 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00009187 diag::err_typecheck_decl_incomplete_type)) {
9188 VDecl->setInvalidDecl();
9189 return;
9190 }
9191
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009192 // The variable can not have an abstract class type.
9193 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9194 diag::err_abstract_type_in_decl,
9195 AbstractVariableType))
9196 VDecl->setInvalidDecl();
9197
Sebastian Redl5ca79842010-02-01 20:16:42 +00009198 const VarDecl *Def;
9199 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009200 Diag(VDecl->getLocation(), diag::err_redefinition)
9201 << VDecl->getDeclName();
9202 Diag(Def->getLocation(), diag::note_previous_definition);
9203 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009204 return;
9205 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00009206
Douglas Gregorf0f83692010-08-24 05:27:49 +00009207 // C++ [class.static.data]p4
9208 // If a static data member is of const integral or const
9209 // enumeration type, its declaration in the class definition can
9210 // specify a constant-initializer which shall be an integral
9211 // constant expression (5.19). In that case, the member can appear
9212 // in integral constant expressions. The member shall still be
9213 // defined in a namespace scope if it is used in the program and the
9214 // namespace scope definition shall not contain an initializer.
9215 //
9216 // We already performed a redefinition check above, but for static
9217 // data members we also need to check whether there was an in-class
9218 // declaration with an initializer.
9219 const VarDecl* PrevInit = 0;
9220 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9221 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9222 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9223 return;
9224 }
9225
Douglas Gregor71f39c92010-12-16 01:31:22 +00009226 bool IsDependent = false;
9227 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9228 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9229 VDecl->setInvalidDecl();
9230 return;
9231 }
9232
9233 if (Exprs.get()[I]->isTypeDependent())
9234 IsDependent = true;
9235 }
9236
Douglas Gregor50dc2192010-02-11 22:55:30 +00009237 // If either the declaration has a dependent type or if any of the
9238 // expressions is type-dependent, we represent the initialization
9239 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00009240 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00009241 // Let clients know that initialization was done with a direct initializer.
9242 VDecl->setCXXDirectInitializer(true);
9243
9244 // Store the initialization expressions as a ParenListExpr.
9245 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00009246 VDecl->setInit(new (Context) ParenListExpr(
9247 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9248 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00009249 return;
9250 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009251
9252 // Capture the variable that is being initialized and the style of
9253 // initialization.
9254 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9255
9256 // FIXME: Poor source location information.
9257 InitializationKind Kind
9258 = InitializationKind::CreateDirect(VDecl->getLocation(),
9259 LParenLoc, RParenLoc);
9260
Douglas Gregorb06fa542011-10-10 16:05:18 +00009261 QualType T = VDecl->getType();
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009262 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00009263 Exprs.get(), Exprs.size());
Douglas Gregorb06fa542011-10-10 16:05:18 +00009264 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009265 if (Result.isInvalid()) {
9266 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009267 return;
Douglas Gregorb06fa542011-10-10 16:05:18 +00009268 } else if (T != VDecl->getType()) {
9269 VDecl->setType(T);
9270 Result.get()->setType(T);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009271 }
John McCallacf0ee52010-10-08 02:01:28 +00009272
Douglas Gregorb06fa542011-10-10 16:05:18 +00009273
Richard Smith2316cd82011-09-29 19:11:37 +00009274 Expr *Init = Result.get();
9275 CheckImplicitConversions(Init, LParenLoc);
Richard Smith2316cd82011-09-29 19:11:37 +00009276
9277 Init = MaybeCreateExprWithCleanups(Init);
9278 VDecl->setInit(Init);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009279 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009280
John McCall8b7fd8f12011-01-19 11:48:09 +00009281 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009282}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009283
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009284/// \brief Given a constructor and the set of arguments provided for the
9285/// constructor, convert the arguments and add any required default arguments
9286/// to form a proper call to this constructor.
9287///
9288/// \returns true if an error occurred, false otherwise.
9289bool
9290Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9291 MultiExprArg ArgsPtr,
9292 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00009293 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009294 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9295 unsigned NumArgs = ArgsPtr.size();
9296 Expr **Args = (Expr **)ArgsPtr.get();
9297
9298 const FunctionProtoType *Proto
9299 = Constructor->getType()->getAs<FunctionProtoType>();
9300 assert(Proto && "Constructor without a prototype?");
9301 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009302
9303 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009304 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009305 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009306 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009307 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009308
9309 VariadicCallType CallType =
9310 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009311 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009312 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9313 Proto, 0, Args, NumArgs, AllArgs,
9314 CallType);
9315 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9316 ConvertedArgs.push_back(AllArgs[i]);
9317 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009318}
9319
Anders Carlssone363c8e2009-12-12 00:32:00 +00009320static inline bool
9321CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9322 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009323 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00009324 if (isa<NamespaceDecl>(DC)) {
9325 return SemaRef.Diag(FnDecl->getLocation(),
9326 diag::err_operator_new_delete_declared_in_namespace)
9327 << FnDecl->getDeclName();
9328 }
9329
9330 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00009331 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009332 return SemaRef.Diag(FnDecl->getLocation(),
9333 diag::err_operator_new_delete_declared_static)
9334 << FnDecl->getDeclName();
9335 }
9336
Anders Carlsson60659a82009-12-12 02:43:16 +00009337 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00009338}
9339
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009340static inline bool
9341CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9342 CanQualType ExpectedResultType,
9343 CanQualType ExpectedFirstParamType,
9344 unsigned DependentParamTypeDiag,
9345 unsigned InvalidParamTypeDiag) {
9346 QualType ResultType =
9347 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9348
9349 // Check that the result type is not dependent.
9350 if (ResultType->isDependentType())
9351 return SemaRef.Diag(FnDecl->getLocation(),
9352 diag::err_operator_new_delete_dependent_result_type)
9353 << FnDecl->getDeclName() << ExpectedResultType;
9354
9355 // Check that the result type is what we expect.
9356 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9357 return SemaRef.Diag(FnDecl->getLocation(),
9358 diag::err_operator_new_delete_invalid_result_type)
9359 << FnDecl->getDeclName() << ExpectedResultType;
9360
9361 // A function template must have at least 2 parameters.
9362 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9363 return SemaRef.Diag(FnDecl->getLocation(),
9364 diag::err_operator_new_delete_template_too_few_parameters)
9365 << FnDecl->getDeclName();
9366
9367 // The function decl must have at least 1 parameter.
9368 if (FnDecl->getNumParams() == 0)
9369 return SemaRef.Diag(FnDecl->getLocation(),
9370 diag::err_operator_new_delete_too_few_parameters)
9371 << FnDecl->getDeclName();
9372
9373 // Check the the first parameter type is not dependent.
9374 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9375 if (FirstParamType->isDependentType())
9376 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9377 << FnDecl->getDeclName() << ExpectedFirstParamType;
9378
9379 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00009380 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009381 ExpectedFirstParamType)
9382 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9383 << FnDecl->getDeclName() << ExpectedFirstParamType;
9384
9385 return false;
9386}
9387
Anders Carlsson12308f42009-12-11 23:23:22 +00009388static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009389CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009390 // C++ [basic.stc.dynamic.allocation]p1:
9391 // A program is ill-formed if an allocation function is declared in a
9392 // namespace scope other than global scope or declared static in global
9393 // scope.
9394 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9395 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009396
9397 CanQualType SizeTy =
9398 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9399
9400 // C++ [basic.stc.dynamic.allocation]p1:
9401 // The return type shall be void*. The first parameter shall have type
9402 // std::size_t.
9403 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9404 SizeTy,
9405 diag::err_operator_new_dependent_param_type,
9406 diag::err_operator_new_param_type))
9407 return true;
9408
9409 // C++ [basic.stc.dynamic.allocation]p1:
9410 // The first parameter shall not have an associated default argument.
9411 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00009412 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009413 diag::err_operator_new_default_arg)
9414 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9415
9416 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00009417}
9418
9419static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00009420CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9421 // C++ [basic.stc.dynamic.deallocation]p1:
9422 // A program is ill-formed if deallocation functions are declared in a
9423 // namespace scope other than global scope or declared static in global
9424 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00009425 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9426 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009427
9428 // C++ [basic.stc.dynamic.deallocation]p2:
9429 // Each deallocation function shall return void and its first parameter
9430 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009431 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9432 SemaRef.Context.VoidPtrTy,
9433 diag::err_operator_delete_dependent_param_type,
9434 diag::err_operator_delete_param_type))
9435 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009436
Anders Carlsson12308f42009-12-11 23:23:22 +00009437 return false;
9438}
9439
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009440/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9441/// of this overloaded operator is well-formed. If so, returns false;
9442/// otherwise, emits appropriate diagnostics and returns true.
9443bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00009444 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009445 "Expected an overloaded operator declaration");
9446
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009447 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9448
Mike Stump11289f42009-09-09 15:08:12 +00009449 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009450 // The allocation and deallocation functions, operator new,
9451 // operator new[], operator delete and operator delete[], are
9452 // described completely in 3.7.3. The attributes and restrictions
9453 // found in the rest of this subclause do not apply to them unless
9454 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00009455 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00009456 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00009457
Anders Carlsson22f443f2009-12-12 00:26:23 +00009458 if (Op == OO_New || Op == OO_Array_New)
9459 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009460
9461 // C++ [over.oper]p6:
9462 // An operator function shall either be a non-static member
9463 // function or be a non-member function and have at least one
9464 // parameter whose type is a class, a reference to a class, an
9465 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00009466 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9467 if (MethodDecl->isStatic())
9468 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009469 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009470 } else {
9471 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00009472 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9473 ParamEnd = FnDecl->param_end();
9474 Param != ParamEnd; ++Param) {
9475 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00009476 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9477 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009478 ClassOrEnumParam = true;
9479 break;
9480 }
9481 }
9482
Douglas Gregord69246b2008-11-17 16:14:12 +00009483 if (!ClassOrEnumParam)
9484 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009485 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009486 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009487 }
9488
9489 // C++ [over.oper]p8:
9490 // An operator function cannot have default arguments (8.3.6),
9491 // except where explicitly stated below.
9492 //
Mike Stump11289f42009-09-09 15:08:12 +00009493 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009494 // (C++ [over.call]p1).
9495 if (Op != OO_Call) {
9496 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9497 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009498 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00009499 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00009500 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009501 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009502 }
9503 }
9504
Douglas Gregor6cf08062008-11-10 13:38:07 +00009505 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9506 { false, false, false }
9507#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9508 , { Unary, Binary, MemberOnly }
9509#include "clang/Basic/OperatorKinds.def"
9510 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009511
Douglas Gregor6cf08062008-11-10 13:38:07 +00009512 bool CanBeUnaryOperator = OperatorUses[Op][0];
9513 bool CanBeBinaryOperator = OperatorUses[Op][1];
9514 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009515
9516 // C++ [over.oper]p8:
9517 // [...] Operator functions cannot have more or fewer parameters
9518 // than the number required for the corresponding operator, as
9519 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00009520 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00009521 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009522 if (Op != OO_Call &&
9523 ((NumParams == 1 && !CanBeUnaryOperator) ||
9524 (NumParams == 2 && !CanBeBinaryOperator) ||
9525 (NumParams < 1) || (NumParams > 2))) {
9526 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009527 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00009528 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009529 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00009530 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009531 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009532 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00009533 assert(CanBeBinaryOperator &&
9534 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009535 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009536 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009537
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009538 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009539 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009540 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009541
Douglas Gregord69246b2008-11-17 16:14:12 +00009542 // Overloaded operators other than operator() cannot be variadic.
9543 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009544 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009545 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009546 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009547 }
9548
9549 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009550 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9551 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009552 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009553 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009554 }
9555
9556 // C++ [over.inc]p1:
9557 // The user-defined function called operator++ implements the
9558 // prefix and postfix ++ operator. If this function is a member
9559 // function with no parameters, or a non-member function with one
9560 // parameter of class or enumeration type, it defines the prefix
9561 // increment operator ++ for objects of that type. If the function
9562 // is a member function with one parameter (which shall be of type
9563 // int) or a non-member function with two parameters (the second
9564 // of which shall be of type int), it defines the postfix
9565 // increment operator ++ for objects of that type.
9566 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9567 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9568 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009569 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009570 ParamIsInt = BT->getKind() == BuiltinType::Int;
9571
Chris Lattner2b786902008-11-21 07:50:02 +00009572 if (!ParamIsInt)
9573 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009574 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009575 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009576 }
9577
Douglas Gregord69246b2008-11-17 16:14:12 +00009578 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009579}
Chris Lattner3b024a32008-12-17 07:09:26 +00009580
Alexis Huntc88db062010-01-13 09:01:02 +00009581/// CheckLiteralOperatorDeclaration - Check whether the declaration
9582/// of this literal operator function is well-formed. If so, returns
9583/// false; otherwise, emits appropriate diagnostics and returns true.
9584bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9585 DeclContext *DC = FnDecl->getDeclContext();
9586 Decl::Kind Kind = DC->getDeclKind();
9587 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9588 Kind != Decl::LinkageSpec) {
9589 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9590 << FnDecl->getDeclName();
9591 return true;
9592 }
9593
9594 bool Valid = false;
9595
Alexis Hunt7dd26172010-04-07 23:11:06 +00009596 // template <char...> type operator "" name() is the only valid template
9597 // signature, and the only valid signature with no parameters.
9598 if (FnDecl->param_size() == 0) {
9599 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9600 // Must have only one template parameter
9601 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9602 if (Params->size() == 1) {
9603 NonTypeTemplateParmDecl *PmDecl =
9604 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009605
Alexis Hunt7dd26172010-04-07 23:11:06 +00009606 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009607 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9608 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9609 Valid = true;
9610 }
9611 }
9612 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009613 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009614 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9615
Alexis Huntc88db062010-01-13 09:01:02 +00009616 QualType T = (*Param)->getType();
9617
Alexis Hunt079a6f72010-04-07 22:57:35 +00009618 // unsigned long long int, long double, and any character type are allowed
9619 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009620 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9621 Context.hasSameType(T, Context.LongDoubleTy) ||
9622 Context.hasSameType(T, Context.CharTy) ||
9623 Context.hasSameType(T, Context.WCharTy) ||
9624 Context.hasSameType(T, Context.Char16Ty) ||
9625 Context.hasSameType(T, Context.Char32Ty)) {
9626 if (++Param == FnDecl->param_end())
9627 Valid = true;
9628 goto FinishedParams;
9629 }
9630
Alexis Hunt079a6f72010-04-07 22:57:35 +00009631 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009632 const PointerType *PT = T->getAs<PointerType>();
9633 if (!PT)
9634 goto FinishedParams;
9635 T = PT->getPointeeType();
9636 if (!T.isConstQualified())
9637 goto FinishedParams;
9638 T = T.getUnqualifiedType();
9639
9640 // Move on to the second parameter;
9641 ++Param;
9642
9643 // If there is no second parameter, the first must be a const char *
9644 if (Param == FnDecl->param_end()) {
9645 if (Context.hasSameType(T, Context.CharTy))
9646 Valid = true;
9647 goto FinishedParams;
9648 }
9649
9650 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9651 // are allowed as the first parameter to a two-parameter function
9652 if (!(Context.hasSameType(T, Context.CharTy) ||
9653 Context.hasSameType(T, Context.WCharTy) ||
9654 Context.hasSameType(T, Context.Char16Ty) ||
9655 Context.hasSameType(T, Context.Char32Ty)))
9656 goto FinishedParams;
9657
9658 // The second and final parameter must be an std::size_t
9659 T = (*Param)->getType().getUnqualifiedType();
9660 if (Context.hasSameType(T, Context.getSizeType()) &&
9661 ++Param == FnDecl->param_end())
9662 Valid = true;
9663 }
9664
9665 // FIXME: This diagnostic is absolutely terrible.
9666FinishedParams:
9667 if (!Valid) {
9668 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9669 << FnDecl->getDeclName();
9670 return true;
9671 }
9672
Douglas Gregor86325ad2011-08-30 22:40:35 +00009673 StringRef LiteralName
9674 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9675 if (LiteralName[0] != '_') {
9676 // C++0x [usrlit.suffix]p1:
9677 // Literal suffix identifiers that do not start with an underscore are
9678 // reserved for future standardization.
9679 bool IsHexFloat = true;
9680 if (LiteralName.size() > 1 &&
9681 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9682 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9683 if (!isdigit(LiteralName[I])) {
9684 IsHexFloat = false;
9685 break;
9686 }
9687 }
9688 }
9689
9690 if (IsHexFloat)
9691 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9692 << LiteralName;
9693 else
9694 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9695 }
9696
Alexis Huntc88db062010-01-13 09:01:02 +00009697 return false;
9698}
9699
Douglas Gregor07665a62009-01-05 19:45:36 +00009700/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9701/// linkage specification, including the language and (if present)
9702/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9703/// the location of the language string literal, which is provided
9704/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9705/// the '{' brace. Otherwise, this linkage specification does not
9706/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009707Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9708 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009709 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009710 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009711 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009712 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009713 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009714 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009715 Language = LinkageSpecDecl::lang_cxx;
9716 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009717 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009718 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009719 }
Mike Stump11289f42009-09-09 15:08:12 +00009720
Chris Lattner438e5012008-12-17 07:13:27 +00009721 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009722
Douglas Gregor07665a62009-01-05 19:45:36 +00009723 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009724 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009725 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009726 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009727 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009728}
9729
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009730/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009731/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9732/// valid, it's the position of the closing '}' brace in a linkage
9733/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009734Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009735 Decl *LinkageSpec,
9736 SourceLocation RBraceLoc) {
9737 if (LinkageSpec) {
9738 if (RBraceLoc.isValid()) {
9739 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9740 LSDecl->setRBraceLoc(RBraceLoc);
9741 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009742 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009743 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009744 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009745}
9746
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009747/// \brief Perform semantic analysis for the variable declaration that
9748/// occurs within a C++ catch clause, returning the newly-created
9749/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009750VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009751 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009752 SourceLocation StartLoc,
9753 SourceLocation Loc,
9754 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009755 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009756 QualType ExDeclType = TInfo->getType();
9757
Sebastian Redl54c04d42008-12-22 19:15:10 +00009758 // Arrays and functions decay.
9759 if (ExDeclType->isArrayType())
9760 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9761 else if (ExDeclType->isFunctionType())
9762 ExDeclType = Context.getPointerType(ExDeclType);
9763
9764 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9765 // The exception-declaration shall not denote a pointer or reference to an
9766 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009767 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009768 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009769 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009770 Invalid = true;
9771 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009772
Sebastian Redl54c04d42008-12-22 19:15:10 +00009773 QualType BaseType = ExDeclType;
9774 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009775 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009776 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009777 BaseType = Ptr->getPointeeType();
9778 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009779 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00009780 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009781 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009782 BaseType = Ref->getPointeeType();
9783 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009784 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009785 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009786 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009787 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00009788 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009789
Mike Stump11289f42009-09-09 15:08:12 +00009790 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009791 RequireNonAbstractType(Loc, ExDeclType,
9792 diag::err_abstract_type_in_decl,
9793 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009794 Invalid = true;
9795
John McCall2ca705e2010-07-24 00:37:23 +00009796 // Only the non-fragile NeXT runtime currently supports C++ catches
9797 // of ObjC types, and no runtime supports catching ObjC types by value.
9798 if (!Invalid && getLangOptions().ObjC1) {
9799 QualType T = ExDeclType;
9800 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9801 T = RT->getPointeeType();
9802
9803 if (T->isObjCObjectType()) {
9804 Diag(Loc, diag::err_objc_object_catch);
9805 Invalid = true;
9806 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009807 if (!getLangOptions().ObjCNonFragileABI)
9808 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009809 }
9810 }
9811
Abramo Bagnaradff19302011-03-08 08:55:46 +00009812 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9813 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009814 ExDecl->setExceptionVariable(true);
9815
Douglas Gregor8ca0c642011-12-10 01:22:52 +00009816 // In ARC, infer 'retaining' for variables of retainable type.
9817 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9818 Invalid = true;
9819
Douglas Gregor750734c2011-07-06 18:14:43 +00009820 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009821 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009822 // C++ [except.handle]p16:
9823 // The object declared in an exception-declaration or, if the
9824 // exception-declaration does not specify a name, a temporary (12.2) is
9825 // copy-initialized (8.5) from the exception object. [...]
9826 // The object is destroyed when the handler exits, after the destruction
9827 // of any automatic objects initialized within the handler.
9828 //
9829 // We just pretend to initialize the object with itself, then make sure
9830 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009831 QualType initType = ExDeclType;
9832
9833 InitializedEntity entity =
9834 InitializedEntity::InitializeVariable(ExDecl);
9835 InitializationKind initKind =
9836 InitializationKind::CreateCopy(Loc, SourceLocation());
9837
9838 Expr *opaqueValue =
9839 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9840 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9841 ExprResult result = sequence.Perform(*this, entity, initKind,
9842 MultiExprArg(&opaqueValue, 1));
9843 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009844 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009845 else {
9846 // If the constructor used was non-trivial, set this as the
9847 // "initializer".
9848 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9849 if (!construct->getConstructor()->isTrivial()) {
9850 Expr *init = MaybeCreateExprWithCleanups(construct);
9851 ExDecl->setInit(init);
9852 }
9853
9854 // And make sure it's destructable.
9855 FinalizeVarWithDestructor(ExDecl, recordType);
9856 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009857 }
9858 }
9859
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009860 if (Invalid)
9861 ExDecl->setInvalidDecl();
9862
9863 return ExDecl;
9864}
9865
9866/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9867/// handler.
John McCall48871652010-08-21 09:40:31 +00009868Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009869 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009870 bool Invalid = D.isInvalidType();
9871
9872 // Check for unexpanded parameter packs.
9873 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9874 UPPC_ExceptionType)) {
9875 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9876 D.getIdentifierLoc());
9877 Invalid = true;
9878 }
9879
Sebastian Redl54c04d42008-12-22 19:15:10 +00009880 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009881 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009882 LookupOrdinaryName,
9883 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009884 // The scope should be freshly made just for us. There is just no way
9885 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009886 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009887 if (PrevDecl->isTemplateParameter()) {
9888 // Maybe we will complain about the shadowed template parameter.
9889 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009890 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009891 }
9892 }
9893
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009894 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009895 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9896 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009897 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009898 }
9899
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009900 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009901 D.getSourceRange().getBegin(),
9902 D.getIdentifierLoc(),
9903 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009904 if (Invalid)
9905 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009906
Sebastian Redl54c04d42008-12-22 19:15:10 +00009907 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009908 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009909 PushOnScopeChains(ExDecl, S);
9910 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009911 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009912
Douglas Gregor758a8692009-06-17 21:51:59 +00009913 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009914 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009915}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009916
Abramo Bagnaraea947882011-03-08 16:41:52 +00009917Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009918 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009919 Expr *AssertMessageExpr_,
9920 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009921 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009922
Anders Carlsson54b26982009-03-14 00:33:21 +00009923 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009924 // In a static_assert-declaration, the constant-expression shall be a
9925 // constant expression that can be contextually converted to bool.
9926 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9927 if (Converted.isInvalid())
9928 return 0;
9929
Richard Smith902ca212011-12-14 23:32:26 +00009930 llvm::APSInt Cond;
Richard Smithf4c51d92012-02-04 09:53:13 +00009931 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9932 PDiag(diag::err_static_assert_expression_is_not_constant),
9933 /*AllowFold=*/false).isInvalid())
John McCall48871652010-08-21 09:40:31 +00009934 return 0;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009935
Richard Smith902ca212011-12-14 23:32:26 +00009936 if (!Cond)
Abramo Bagnaraea947882011-03-08 16:41:52 +00009937 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009938 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009939 }
Mike Stump11289f42009-09-09 15:08:12 +00009940
Douglas Gregoref68fee2010-12-15 23:55:21 +00009941 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9942 return 0;
9943
Abramo Bagnaraea947882011-03-08 16:41:52 +00009944 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9945 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009946
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009947 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009948 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009949}
Sebastian Redlf769df52009-03-24 22:27:57 +00009950
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009951/// \brief Perform semantic analysis of the given friend type declaration.
9952///
9953/// \returns A friend declaration that.
Abramo Bagnara254b6302011-10-29 20:52:52 +00009954FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9955 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009956 TypeSourceInfo *TSInfo) {
9957 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9958
9959 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009960 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009961
Richard Smithc8239732011-10-18 21:39:00 +00009962 // C++03 [class.friend]p2:
9963 // An elaborated-type-specifier shall be used in a friend declaration
9964 // for a class.*
9965 //
9966 // * The class-key of the elaborated-type-specifier is required.
9967 if (!ActiveTemplateInstantiations.empty()) {
9968 // Do not complain about the form of friend template types during
9969 // template instantiation; we will already have complained when the
9970 // template was declared.
9971 } else if (!T->isElaboratedTypeSpecifier()) {
9972 // If we evaluated the type to a record type, suggest putting
9973 // a tag in front.
9974 if (const RecordType *RT = T->getAs<RecordType>()) {
9975 RecordDecl *RD = RT->getDecl();
9976
9977 std::string InsertionText = std::string(" ") + RD->getKindName();
9978
9979 Diag(TypeRange.getBegin(),
9980 getLangOptions().CPlusPlus0x ?
9981 diag::warn_cxx98_compat_unelaborated_friend_type :
9982 diag::ext_unelaborated_friend_type)
9983 << (unsigned) RD->getTagKind()
9984 << T
9985 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9986 InsertionText);
9987 } else {
9988 Diag(FriendLoc,
9989 getLangOptions().CPlusPlus0x ?
9990 diag::warn_cxx98_compat_nonclass_type_friend :
9991 diag::ext_nonclass_type_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009992 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009993 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009994 }
Richard Smithc8239732011-10-18 21:39:00 +00009995 } else if (T->getAs<EnumType>()) {
9996 Diag(FriendLoc,
9997 getLangOptions().CPlusPlus0x ?
9998 diag::warn_cxx98_compat_enum_friend :
9999 diag::ext_enum_friend)
10000 << T
10001 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010002 }
10003
Douglas Gregor3b4abb62010-04-07 17:57:12 +000010004 // C++0x [class.friend]p3:
10005 // If the type specifier in a friend declaration designates a (possibly
10006 // cv-qualified) class type, that class is declared as a friend; otherwise,
10007 // the friend declaration is ignored.
10008
10009 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10010 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010011
Abramo Bagnara254b6302011-10-29 20:52:52 +000010012 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010013}
10014
John McCallace48cd2010-10-19 01:40:49 +000010015/// Handle a friend tag declaration where the scope specifier was
10016/// templated.
10017Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10018 unsigned TagSpec, SourceLocation TagLoc,
10019 CXXScopeSpec &SS,
10020 IdentifierInfo *Name, SourceLocation NameLoc,
10021 AttributeList *Attr,
10022 MultiTemplateParamsArg TempParamLists) {
10023 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10024
10025 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000010026 bool Invalid = false;
10027
10028 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +000010029 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +000010030 TempParamLists.get(),
10031 TempParamLists.size(),
10032 /*friend*/ true,
10033 isExplicitSpecialization,
10034 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000010035 if (TemplateParams->size() > 0) {
10036 // This is a declaration of a class template.
10037 if (Invalid)
10038 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010039
Eric Christopher6f228b52011-07-21 05:34:24 +000010040 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10041 SS, Name, NameLoc, Attr,
10042 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000010043 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000010044 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010045 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +000010046 } else {
10047 // The "template<>" header is extraneous.
10048 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10049 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10050 isExplicitSpecialization = true;
10051 }
10052 }
10053
10054 if (Invalid) return 0;
10055
John McCallace48cd2010-10-19 01:40:49 +000010056 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000010057 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +000010058 if (TempParamLists.get()[I]->size()) {
10059 isAllExplicitSpecializations = false;
10060 break;
10061 }
10062 }
10063
10064 // FIXME: don't ignore attributes.
10065
10066 // If it's explicit specializations all the way down, just forget
10067 // about the template header and build an appropriate non-templated
10068 // friend. TODO: for source fidelity, remember the headers.
10069 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010070 if (SS.isEmpty()) {
10071 bool Owned = false;
10072 bool IsDependent = false;
10073 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10074 Attr, AS_public,
10075 /*ModulePrivateLoc=*/SourceLocation(),
10076 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010077 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010078 /*ScopedEnumUsesClassTag=*/false,
10079 /*UnderlyingType=*/TypeResult());
10080 }
10081
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010082 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000010083 ElaboratedTypeKeyword Keyword
10084 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010085 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000010086 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000010087 if (T.isNull())
10088 return 0;
10089
10090 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10091 if (isa<DependentNameType>(T)) {
10092 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000010093 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010094 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000010095 TL.setNameLoc(NameLoc);
10096 } else {
10097 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000010098 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000010099 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000010100 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10101 }
10102
10103 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10104 TSI, FriendLoc);
10105 Friend->setAccess(AS_public);
10106 CurContext->addDecl(Friend);
10107 return Friend;
10108 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010109
10110 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10111
10112
John McCallace48cd2010-10-19 01:40:49 +000010113
10114 // Handle the case of a templated-scope friend class. e.g.
10115 // template <class T> class A<T>::B;
10116 // FIXME: we don't support these right now.
10117 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10118 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10119 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10120 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000010121 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010122 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000010123 TL.setNameLoc(NameLoc);
10124
10125 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10126 TSI, FriendLoc);
10127 Friend->setAccess(AS_public);
10128 Friend->setUnsupportedFriend(true);
10129 CurContext->addDecl(Friend);
10130 return Friend;
10131}
10132
10133
John McCall11083da2009-09-16 22:47:08 +000010134/// Handle a friend type declaration. This works in tandem with
10135/// ActOnTag.
10136///
10137/// Notes on friend class templates:
10138///
10139/// We generally treat friend class declarations as if they were
10140/// declaring a class. So, for example, the elaborated type specifier
10141/// in a friend declaration is required to obey the restrictions of a
10142/// class-head (i.e. no typedefs in the scope chain), template
10143/// parameters are required to match up with simple template-ids, &c.
10144/// However, unlike when declaring a template specialization, it's
10145/// okay to refer to a template specialization without an empty
10146/// template parameter declaration, e.g.
10147/// friend class A<T>::B<unsigned>;
10148/// We permit this as a special case; if there are any template
10149/// parameters present at all, require proper matching, i.e.
10150/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000010151Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000010152 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010153 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +000010154
10155 assert(DS.isFriendSpecified());
10156 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10157
John McCall11083da2009-09-16 22:47:08 +000010158 // Try to convert the decl specifier to a type. This works for
10159 // friend templates because ActOnTag never produces a ClassTemplateDecl
10160 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000010161 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000010162 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10163 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000010164 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000010165 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010166
Douglas Gregor6c110f32010-12-16 01:14:37 +000010167 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10168 return 0;
10169
John McCall11083da2009-09-16 22:47:08 +000010170 // This is definitely an error in C++98. It's probably meant to
10171 // be forbidden in C++0x, too, but the specification is just
10172 // poorly written.
10173 //
10174 // The problem is with declarations like the following:
10175 // template <T> friend A<T>::foo;
10176 // where deciding whether a class C is a friend or not now hinges
10177 // on whether there exists an instantiation of A that causes
10178 // 'foo' to equal C. There are restrictions on class-heads
10179 // (which we declare (by fiat) elaborated friend declarations to
10180 // be) that makes this tractable.
10181 //
10182 // FIXME: handle "template <> friend class A<T>;", which
10183 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000010184 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000010185 Diag(Loc, diag::err_tagless_friend_type_template)
10186 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010187 return 0;
John McCall11083da2009-09-16 22:47:08 +000010188 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010189
John McCallaa74a0c2009-08-28 07:59:38 +000010190 // C++98 [class.friend]p1: A friend of a class is a function
10191 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000010192 // This is fixed in DR77, which just barely didn't make the C++03
10193 // deadline. It's also a very silly restriction that seriously
10194 // affects inner classes and which nobody else seems to implement;
10195 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000010196 //
10197 // But note that we could warn about it: it's always useless to
10198 // friend one of your own members (it's not, however, worthless to
10199 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000010200
John McCall11083da2009-09-16 22:47:08 +000010201 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010202 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000010203 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010204 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +000010205 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +000010206 TSI,
John McCall11083da2009-09-16 22:47:08 +000010207 DS.getFriendSpecLoc());
10208 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000010209 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010210
10211 if (!D)
John McCall48871652010-08-21 09:40:31 +000010212 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010213
John McCall11083da2009-09-16 22:47:08 +000010214 D->setAccess(AS_public);
10215 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000010216
John McCall48871652010-08-21 09:40:31 +000010217 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000010218}
10219
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010220Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCallde3fd222010-10-12 23:13:28 +000010221 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010222 const DeclSpec &DS = D.getDeclSpec();
10223
10224 assert(DS.isFriendSpecified());
10225 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10226
10227 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000010228 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000010229
10230 // C++ [class.friend]p1
10231 // A friend of a class is a function or class....
10232 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000010233 // It *doesn't* see through dependent types, which is correct
10234 // according to [temp.arg.type]p3:
10235 // If a declaration acquires a function type through a
10236 // type dependent on a template-parameter and this causes
10237 // a declaration that does not use the syntactic form of a
10238 // function declarator to have a function type, the program
10239 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010240 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000010241 Diag(Loc, diag::err_unexpected_friend);
10242
10243 // It might be worthwhile to try to recover by creating an
10244 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000010245 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010246 }
10247
10248 // C++ [namespace.memdef]p3
10249 // - If a friend declaration in a non-local class first declares a
10250 // class or function, the friend class or function is a member
10251 // of the innermost enclosing namespace.
10252 // - The name of the friend is not found by simple name lookup
10253 // until a matching declaration is provided in that namespace
10254 // scope (either before or after the class declaration granting
10255 // friendship).
10256 // - If a friend function is called, its name may be found by the
10257 // name lookup that considers functions from namespaces and
10258 // classes associated with the types of the function arguments.
10259 // - When looking for a prior declaration of a class or a function
10260 // declared as a friend, scopes outside the innermost enclosing
10261 // namespace scope are not considered.
10262
John McCallde3fd222010-10-12 23:13:28 +000010263 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010264 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10265 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000010266 assert(Name);
10267
Douglas Gregor6c110f32010-12-16 01:14:37 +000010268 // Check for unexpanded parameter packs.
10269 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10270 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10271 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10272 return 0;
10273
John McCall07e91c02009-08-06 02:15:43 +000010274 // The context we found the declaration in, or in which we should
10275 // create the declaration.
10276 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000010277 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010278 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000010279 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000010280
John McCallde3fd222010-10-12 23:13:28 +000010281 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +000010282
John McCallde3fd222010-10-12 23:13:28 +000010283 // There are four cases here.
10284 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +000010285 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +000010286 // there as appropriate.
10287 // Recover from invalid scope qualifiers as if they just weren't there.
10288 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +000010289 // C++0x [namespace.memdef]p3:
10290 // If the name in a friend declaration is neither qualified nor
10291 // a template-id and the declaration is a function or an
10292 // elaborated-type-specifier, the lookup to determine whether
10293 // the entity has been previously declared shall not consider
10294 // any scopes outside the innermost enclosing namespace.
10295 // C++0x [class.friend]p11:
10296 // If a friend declaration appears in a local class and the name
10297 // specified is an unqualified name, a prior declaration is
10298 // looked up without considering scopes that are outside the
10299 // innermost enclosing non-class scope. For a friend function
10300 // declaration, if there is no prior declaration, the program is
10301 // ill-formed.
10302 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +000010303 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000010304
John McCallf7cfb222010-10-13 05:45:15 +000010305 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000010306 DC = CurContext;
10307 while (true) {
10308 // Skip class contexts. If someone can cite chapter and verse
10309 // for this behavior, that would be nice --- it's what GCC and
10310 // EDG do, and it seems like a reasonable intent, but the spec
10311 // really only says that checks for unqualified existing
10312 // declarations should stop at the nearest enclosing namespace,
10313 // not that they should only consider the nearest enclosing
10314 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010315 while (DC->isRecord())
10316 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000010317
John McCall1f82f242009-11-18 22:49:29 +000010318 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +000010319
10320 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +000010321 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +000010322 break;
John McCallf7cfb222010-10-13 05:45:15 +000010323
John McCallf4776592010-10-14 22:22:28 +000010324 if (isTemplateId) {
10325 if (isa<TranslationUnitDecl>(DC)) break;
10326 } else {
10327 if (DC->isFileContext()) break;
10328 }
John McCall07e91c02009-08-06 02:15:43 +000010329 DC = DC->getParent();
10330 }
10331
10332 // C++ [class.friend]p1: A friend of a class is a function or
10333 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010334 // C++11 changes this for both friend types and functions.
John McCall93343b92009-08-06 20:49:32 +000010335 // Most C++ 98 compilers do seem to give an error here, so
10336 // we do, too.
Richard Smith0bf8a4922011-10-18 20:49:44 +000010337 if (!Previous.empty() && DC->Equals(CurContext))
10338 Diag(DS.getFriendSpecLoc(),
10339 getLangOptions().CPlusPlus0x ?
10340 diag::warn_cxx98_compat_friend_is_member :
10341 diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +000010342
John McCallccbc0322010-10-13 06:22:15 +000010343 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregordd847ba2011-11-03 16:37:14 +000010344
Douglas Gregor16e65612011-10-10 01:11:59 +000010345 // C++ [class.friend]p6:
10346 // A function can be defined in a friend declaration of a class if and
10347 // only if the class is a non-local class (9.8), the function name is
10348 // unqualified, and the function has namespace scope.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010349 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010350 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10351 }
10352
John McCallde3fd222010-10-12 23:13:28 +000010353 // - There's a non-dependent scope specifier, in which case we
10354 // compute it and do a previous lookup there for a function
10355 // or function template.
10356 } else if (!SS.getScopeRep()->isDependent()) {
10357 DC = computeDeclContext(SS);
10358 if (!DC) return 0;
10359
10360 if (RequireCompleteDeclContext(SS, DC)) return 0;
10361
10362 LookupQualifiedName(Previous, DC);
10363
10364 // Ignore things found implicitly in the wrong scope.
10365 // TODO: better diagnostics for this case. Suggesting the right
10366 // qualified scope would be nice...
10367 LookupResult::Filter F = Previous.makeFilter();
10368 while (F.hasNext()) {
10369 NamedDecl *D = F.next();
10370 if (!DC->InEnclosingNamespaceSetOf(
10371 D->getDeclContext()->getRedeclContext()))
10372 F.erase();
10373 }
10374 F.done();
10375
10376 if (Previous.empty()) {
10377 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010378 Diag(Loc, diag::err_qualified_friend_not_found)
10379 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000010380 return 0;
10381 }
10382
10383 // C++ [class.friend]p1: A friend of a class is a function or
10384 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010385 if (DC->Equals(CurContext))
10386 Diag(DS.getFriendSpecLoc(),
10387 getLangOptions().CPlusPlus0x ?
10388 diag::warn_cxx98_compat_friend_is_member :
10389 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000010390
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010391 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010392 // C++ [class.friend]p6:
10393 // A function can be defined in a friend declaration of a class if and
10394 // only if the class is a non-local class (9.8), the function name is
10395 // unqualified, and the function has namespace scope.
10396 SemaDiagnosticBuilder DB
10397 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10398
10399 DB << SS.getScopeRep();
10400 if (DC->isFileContext())
10401 DB << FixItHint::CreateRemoval(SS.getRange());
10402 SS.clear();
10403 }
John McCallde3fd222010-10-12 23:13:28 +000010404
10405 // - There's a scope specifier that does not match any template
10406 // parameter lists, in which case we use some arbitrary context,
10407 // create a method or method template, and wait for instantiation.
10408 // - There's a scope specifier that does match some template
10409 // parameter lists, which we don't handle right now.
10410 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010411 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010412 // C++ [class.friend]p6:
10413 // A function can be defined in a friend declaration of a class if and
10414 // only if the class is a non-local class (9.8), the function name is
10415 // unqualified, and the function has namespace scope.
10416 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10417 << SS.getScopeRep();
10418 }
10419
John McCallde3fd222010-10-12 23:13:28 +000010420 DC = CurContext;
10421 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000010422 }
Douglas Gregor16e65612011-10-10 01:11:59 +000010423
John McCallf7cfb222010-10-13 05:45:15 +000010424 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000010425 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000010426 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10427 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10428 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000010429 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000010430 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10431 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000010432 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010433 }
John McCall07e91c02009-08-06 02:15:43 +000010434 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010435
Douglas Gregordd847ba2011-11-03 16:37:14 +000010436 // FIXME: This is an egregious hack to cope with cases where the scope stack
10437 // does not contain the declaration context, i.e., in an out-of-line
10438 // definition of a class.
10439 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10440 if (!DCScope) {
10441 FakeDCScope.setEntity(DC);
10442 DCScope = &FakeDCScope;
10443 }
10444
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010445 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010446 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10447 move(TemplateParams), AddToScope);
John McCall48871652010-08-21 09:40:31 +000010448 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000010449
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010450 assert(ND->getDeclContext() == DC);
10451 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000010452
John McCall759e32b2009-08-31 22:39:49 +000010453 // Add the function declaration to the appropriate lookup tables,
10454 // adjusting the redeclarations list as necessary. We don't
10455 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000010456 //
John McCall759e32b2009-08-31 22:39:49 +000010457 // Also update the scope-based lookup if the target context's
10458 // lookup context is in lexical scope.
10459 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010460 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010461 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010462 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010463 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010464 }
John McCallaa74a0c2009-08-28 07:59:38 +000010465
10466 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010467 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000010468 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000010469 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000010470 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000010471
John McCallde3fd222010-10-12 23:13:28 +000010472 if (ND->isInvalidDecl())
10473 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +000010474 else {
10475 FunctionDecl *FD;
10476 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10477 FD = FTD->getTemplatedDecl();
10478 else
10479 FD = cast<FunctionDecl>(ND);
10480
10481 // Mark templated-scope function declarations as unsupported.
10482 if (FD->getNumTemplateParameterLists())
10483 FrD->setUnsupportedFriend(true);
10484 }
John McCallde3fd222010-10-12 23:13:28 +000010485
John McCall48871652010-08-21 09:40:31 +000010486 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000010487}
10488
John McCall48871652010-08-21 09:40:31 +000010489void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10490 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000010491
Sebastian Redlf769df52009-03-24 22:27:57 +000010492 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10493 if (!Fn) {
10494 Diag(DelLoc, diag::err_deleted_non_function);
10495 return;
10496 }
Douglas Gregorec9fd132012-01-14 16:38:05 +000010497 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redlf769df52009-03-24 22:27:57 +000010498 Diag(DelLoc, diag::err_deleted_decl_not_first);
10499 Diag(Prev->getLocation(), diag::note_previous_declaration);
10500 // If the declaration wasn't the first, we delete the function anyway for
10501 // recovery.
10502 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010503 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000010504}
Sebastian Redl4c018662009-04-27 21:33:24 +000010505
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010506void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10507 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10508
10509 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000010510 if (MD->getParent()->isDependentType()) {
10511 MD->setDefaulted();
10512 MD->setExplicitlyDefaulted();
10513 return;
10514 }
10515
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010516 CXXSpecialMember Member = getSpecialMember(MD);
10517 if (Member == CXXInvalid) {
10518 Diag(DefaultLoc, diag::err_default_special_members);
10519 return;
10520 }
10521
10522 MD->setDefaulted();
10523 MD->setExplicitlyDefaulted();
10524
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010525 // If this definition appears within the record, do the checking when
10526 // the record is complete.
10527 const FunctionDecl *Primary = MD;
10528 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10529 // Find the uninstantiated declaration that actually had the '= default'
10530 // on it.
10531 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10532
10533 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010534 return;
10535
10536 switch (Member) {
10537 case CXXDefaultConstructor: {
10538 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10539 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010540 if (!CD->isInvalidDecl())
10541 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10542 break;
10543 }
10544
10545 case CXXCopyConstructor: {
10546 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10547 CheckExplicitlyDefaultedCopyConstructor(CD);
10548 if (!CD->isInvalidDecl())
10549 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010550 break;
10551 }
Alexis Huntf91729462011-05-12 22:46:25 +000010552
Alexis Huntc9a55732011-05-14 05:23:28 +000010553 case CXXCopyAssignment: {
10554 CheckExplicitlyDefaultedCopyAssignment(MD);
10555 if (!MD->isInvalidDecl())
10556 DefineImplicitCopyAssignment(DefaultLoc, MD);
10557 break;
10558 }
10559
Alexis Huntf91729462011-05-12 22:46:25 +000010560 case CXXDestructor: {
10561 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10562 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010563 if (!DD->isInvalidDecl())
10564 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000010565 break;
10566 }
10567
Sebastian Redl22653ba2011-08-30 19:58:05 +000010568 case CXXMoveConstructor: {
10569 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10570 CheckExplicitlyDefaultedMoveConstructor(CD);
10571 if (!CD->isInvalidDecl())
10572 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000010573 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010574 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000010575
Sebastian Redl22653ba2011-08-30 19:58:05 +000010576 case CXXMoveAssignment: {
10577 CheckExplicitlyDefaultedMoveAssignment(MD);
10578 if (!MD->isInvalidDecl())
10579 DefineImplicitMoveAssignment(DefaultLoc, MD);
10580 break;
10581 }
10582
10583 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000010584 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010585 }
10586 } else {
10587 Diag(DefaultLoc, diag::err_default_special_members);
10588 }
10589}
10590
Sebastian Redl4c018662009-04-27 21:33:24 +000010591static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000010592 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000010593 Stmt *SubStmt = *CI;
10594 if (!SubStmt)
10595 continue;
10596 if (isa<ReturnStmt>(SubStmt))
10597 Self.Diag(SubStmt->getSourceRange().getBegin(),
10598 diag::err_return_in_constructor_handler);
10599 if (!isa<Expr>(SubStmt))
10600 SearchForReturnInStmt(Self, SubStmt);
10601 }
10602}
10603
10604void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10605 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10606 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10607 SearchForReturnInStmt(*this, Handler);
10608 }
10609}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010610
Mike Stump11289f42009-09-09 15:08:12 +000010611bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010612 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010613 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10614 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010615
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010616 if (Context.hasSameType(NewTy, OldTy) ||
10617 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010618 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010619
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010620 // Check if the return types are covariant
10621 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010622
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010623 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010624 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10625 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010626 NewClassTy = NewPT->getPointeeType();
10627 OldClassTy = OldPT->getPointeeType();
10628 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010629 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10630 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10631 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10632 NewClassTy = NewRT->getPointeeType();
10633 OldClassTy = OldRT->getPointeeType();
10634 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010635 }
10636 }
Mike Stump11289f42009-09-09 15:08:12 +000010637
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010638 // The return types aren't either both pointers or references to a class type.
10639 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010640 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010641 diag::err_different_return_type_for_overriding_virtual_function)
10642 << New->getDeclName() << NewTy << OldTy;
10643 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010644
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010645 return true;
10646 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010647
Anders Carlssone60365b2009-12-31 18:34:24 +000010648 // C++ [class.virtual]p6:
10649 // If the return type of D::f differs from the return type of B::f, the
10650 // class type in the return type of D::f shall be complete at the point of
10651 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010652 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10653 if (!RT->isBeingDefined() &&
10654 RequireCompleteType(New->getLocation(), NewClassTy,
10655 PDiag(diag::err_covariant_return_incomplete)
10656 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010657 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010658 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010659
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010660 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010661 // Check if the new class derives from the old class.
10662 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10663 Diag(New->getLocation(),
10664 diag::err_covariant_return_not_derived)
10665 << New->getDeclName() << NewTy << OldTy;
10666 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10667 return true;
10668 }
Mike Stump11289f42009-09-09 15:08:12 +000010669
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010670 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010671 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010672 diag::err_covariant_return_inaccessible_base,
10673 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10674 // FIXME: Should this point to the return type?
10675 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010676 // FIXME: this note won't trigger for delayed access control
10677 // diagnostics, and it's impossible to get an undelayed error
10678 // here from access control during the original parse because
10679 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010680 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10681 return true;
10682 }
10683 }
Mike Stump11289f42009-09-09 15:08:12 +000010684
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010685 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010686 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010687 Diag(New->getLocation(),
10688 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010689 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010690 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10691 return true;
10692 };
Mike Stump11289f42009-09-09 15:08:12 +000010693
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010694
10695 // The new class type must have the same or less qualifiers as the old type.
10696 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10697 Diag(New->getLocation(),
10698 diag::err_covariant_return_type_class_type_more_qualified)
10699 << New->getDeclName() << NewTy << OldTy;
10700 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10701 return true;
10702 };
Mike Stump11289f42009-09-09 15:08:12 +000010703
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010704 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010705}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010706
Douglas Gregor21920e372009-12-01 17:24:26 +000010707/// \brief Mark the given method pure.
10708///
10709/// \param Method the method to be marked pure.
10710///
10711/// \param InitRange the source range that covers the "0" initializer.
10712bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010713 SourceLocation EndLoc = InitRange.getEnd();
10714 if (EndLoc.isValid())
10715 Method->setRangeEnd(EndLoc);
10716
Douglas Gregor21920e372009-12-01 17:24:26 +000010717 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10718 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010719 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010720 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010721
10722 if (!Method->isInvalidDecl())
10723 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10724 << Method->getDeclName() << InitRange;
10725 return true;
10726}
10727
John McCall1f4ee7b2009-12-19 09:28:58 +000010728/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10729/// an initializer for the out-of-line declaration 'Dcl'. The scope
10730/// is a fresh scope pushed for just this purpose.
10731///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010732/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10733/// static data member of class X, names should be looked up in the scope of
10734/// class X.
John McCall48871652010-08-21 09:40:31 +000010735void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010736 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010737 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010738
John McCall1f4ee7b2009-12-19 09:28:58 +000010739 // We should only get called for declarations with scope specifiers, like:
10740 // int foo::bar;
10741 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010742 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010743}
10744
10745/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010746/// initializer for the out-of-line declaration 'D'.
10747void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010748 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010749 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010750
John McCall1f4ee7b2009-12-19 09:28:58 +000010751 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010752 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010753}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010754
10755/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10756/// C++ if/switch/while/for statement.
10757/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010758DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010759 // C++ 6.4p2:
10760 // The declarator shall not specify a function or an array.
10761 // The type-specifier-seq shall not contain typedef and shall not declare a
10762 // new class or enumeration.
10763 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10764 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010765
10766 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010767 if (!Dcl)
10768 return true;
10769
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010770 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10771 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010772 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010773 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010774 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010775
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010776 return Dcl;
10777}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010778
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010779void Sema::LoadExternalVTableUses() {
10780 if (!ExternalSource)
10781 return;
10782
10783 SmallVector<ExternalVTableUse, 4> VTables;
10784 ExternalSource->ReadUsedVTables(VTables);
10785 SmallVector<VTableUse, 4> NewUses;
10786 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10787 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10788 = VTablesUsed.find(VTables[I].Record);
10789 // Even if a definition wasn't required before, it may be required now.
10790 if (Pos != VTablesUsed.end()) {
10791 if (!Pos->second && VTables[I].DefinitionRequired)
10792 Pos->second = true;
10793 continue;
10794 }
10795
10796 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10797 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10798 }
10799
10800 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10801}
10802
Douglas Gregor88d292c2010-05-13 16:44:06 +000010803void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10804 bool DefinitionRequired) {
10805 // Ignore any vtable uses in unevaluated operands or for classes that do
10806 // not have a vtable.
10807 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10808 CurContext->isDependentContext() ||
Eli Friedman02b58512012-01-21 04:44:06 +000010809 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010810 return;
10811
Douglas Gregor88d292c2010-05-13 16:44:06 +000010812 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010813 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010814 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10815 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10816 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10817 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010818 // If we already had an entry, check to see if we are promoting this vtable
10819 // to required a definition. If so, we need to reappend to the VTableUses
10820 // list, since we may have already processed the first entry.
10821 if (DefinitionRequired && !Pos.first->second) {
10822 Pos.first->second = true;
10823 } else {
10824 // Otherwise, we can early exit.
10825 return;
10826 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010827 }
10828
10829 // Local classes need to have their virtual members marked
10830 // immediately. For all other classes, we mark their virtual members
10831 // at the end of the translation unit.
10832 if (Class->isLocalClass())
10833 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010834 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010835 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010836}
10837
Douglas Gregor88d292c2010-05-13 16:44:06 +000010838bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010839 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010840 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010841 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010842
Douglas Gregor88d292c2010-05-13 16:44:06 +000010843 // Note: The VTableUses vector could grow as a result of marking
10844 // the members of a class as "used", so we check the size each
10845 // time through the loop and prefer indices (with are stable) to
10846 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010847 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010848 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010849 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010850 if (!Class)
10851 continue;
10852
10853 SourceLocation Loc = VTableUses[I].second;
10854
10855 // If this class has a key function, but that key function is
10856 // defined in another translation unit, we don't need to emit the
10857 // vtable even though we're using it.
10858 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010859 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010860 switch (KeyFunction->getTemplateSpecializationKind()) {
10861 case TSK_Undeclared:
10862 case TSK_ExplicitSpecialization:
10863 case TSK_ExplicitInstantiationDeclaration:
10864 // The key function is in another translation unit.
10865 continue;
10866
10867 case TSK_ExplicitInstantiationDefinition:
10868 case TSK_ImplicitInstantiation:
10869 // We will be instantiating the key function.
10870 break;
10871 }
10872 } else if (!KeyFunction) {
10873 // If we have a class with no key function that is the subject
10874 // of an explicit instantiation declaration, suppress the
10875 // vtable; it will live with the explicit instantiation
10876 // definition.
10877 bool IsExplicitInstantiationDeclaration
10878 = Class->getTemplateSpecializationKind()
10879 == TSK_ExplicitInstantiationDeclaration;
10880 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10881 REnd = Class->redecls_end();
10882 R != REnd; ++R) {
10883 TemplateSpecializationKind TSK
10884 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10885 if (TSK == TSK_ExplicitInstantiationDeclaration)
10886 IsExplicitInstantiationDeclaration = true;
10887 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10888 IsExplicitInstantiationDeclaration = false;
10889 break;
10890 }
10891 }
10892
10893 if (IsExplicitInstantiationDeclaration)
10894 continue;
10895 }
10896
10897 // Mark all of the virtual members of this class as referenced, so
10898 // that we can build a vtable. Then, tell the AST consumer that a
10899 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010900 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010901 MarkVirtualMembersReferenced(Loc, Class);
10902 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10903 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10904
10905 // Optionally warn if we're emitting a weak vtable.
10906 if (Class->getLinkage() == ExternalLinkage &&
10907 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010908 const FunctionDecl *KeyFunctionDef = 0;
10909 if (!KeyFunction ||
10910 (KeyFunction->hasBody(KeyFunctionDef) &&
10911 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000010912 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10913 TSK_ExplicitInstantiationDefinition
10914 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10915 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010916 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010917 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010918 VTableUses.clear();
10919
Douglas Gregor97509692011-04-22 22:25:37 +000010920 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010921}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010922
Rafael Espindola5b334082010-03-26 00:36:59 +000010923void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10924 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010925 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10926 e = RD->method_end(); i != e; ++i) {
10927 CXXMethodDecl *MD = *i;
10928
10929 // C++ [basic.def.odr]p2:
10930 // [...] A virtual member function is used if it is not pure. [...]
10931 if (MD->isVirtual() && !MD->isPure())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010932 MarkFunctionReferenced(Loc, MD);
Anders Carlsson82fccd02009-12-07 08:24:59 +000010933 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010934
10935 // Only classes that have virtual bases need a VTT.
10936 if (RD->getNumVBases() == 0)
10937 return;
10938
10939 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10940 e = RD->bases_end(); i != e; ++i) {
10941 const CXXRecordDecl *Base =
10942 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010943 if (Base->getNumVBases() == 0)
10944 continue;
10945 MarkVirtualMembersReferenced(Loc, Base);
10946 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010947}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010948
10949/// SetIvarInitializers - This routine builds initialization ASTs for the
10950/// Objective-C implementation whose ivars need be initialized.
10951void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10952 if (!getLangOptions().CPlusPlus)
10953 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010954 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010955 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010956 CollectIvarsToConstructOrDestruct(OID, ivars);
10957 if (ivars.empty())
10958 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010959 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010960 for (unsigned i = 0; i < ivars.size(); i++) {
10961 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010962 if (Field->isInvalidDecl())
10963 continue;
10964
Alexis Hunt1d792652011-01-08 20:30:50 +000010965 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010966 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10967 InitializationKind InitKind =
10968 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10969
10970 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010971 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010972 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010973 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010974 // Note, MemberInit could actually come back empty if no initialization
10975 // is required (e.g., because it would call a trivial default constructor)
10976 if (!MemberInit.get() || MemberInit.isInvalid())
10977 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010978
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010979 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010980 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10981 SourceLocation(),
10982 MemberInit.takeAs<Expr>(),
10983 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010984 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010985
10986 // Be sure that the destructor is accessible and is marked as referenced.
10987 if (const RecordType *RecordTy
10988 = Context.getBaseElementType(Field->getType())
10989 ->getAs<RecordType>()) {
10990 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010991 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010992 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000010993 CheckDestructorAccess(Field->getLocation(), Destructor,
10994 PDiag(diag::err_access_dtor_ivar)
10995 << Context.getBaseElementType(Field->getType()));
10996 }
10997 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010998 }
10999 ObjCImplementation->setIvarInitializers(Context,
11000 AllToInit.data(), AllToInit.size());
11001 }
11002}
Alexis Hunt6118d662011-05-04 05:57:24 +000011003
Alexis Hunt27a761d2011-05-04 23:29:54 +000011004static
11005void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11006 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11007 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11008 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11009 Sema &S) {
11010 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11011 CE = Current.end();
11012 if (Ctor->isInvalidDecl())
11013 return;
11014
11015 const FunctionDecl *FNTarget = 0;
11016 CXXConstructorDecl *Target;
11017
11018 // We ignore the result here since if we don't have a body, Target will be
11019 // null below.
11020 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11021 Target
11022= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11023
11024 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11025 // Avoid dereferencing a null pointer here.
11026 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11027
11028 if (!Current.insert(Canonical))
11029 return;
11030
11031 // We know that beyond here, we aren't chaining into a cycle.
11032 if (!Target || !Target->isDelegatingConstructor() ||
11033 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11034 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11035 Valid.insert(*CI);
11036 Current.clear();
11037 // We've hit a cycle.
11038 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11039 Current.count(TCanonical)) {
11040 // If we haven't diagnosed this cycle yet, do so now.
11041 if (!Invalid.count(TCanonical)) {
11042 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000011043 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000011044 << Ctor;
11045
11046 // Don't add a note for a function delegating directo to itself.
11047 if (TCanonical != Canonical)
11048 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11049
11050 CXXConstructorDecl *C = Target;
11051 while (C->getCanonicalDecl() != Canonical) {
11052 (void)C->getTargetConstructor()->hasBody(FNTarget);
11053 assert(FNTarget && "Ctor cycle through bodiless function");
11054
11055 C
11056 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11057 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11058 }
11059 }
11060
11061 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11062 Invalid.insert(*CI);
11063 Current.clear();
11064 } else {
11065 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11066 }
11067}
11068
11069
Alexis Hunt6118d662011-05-04 05:57:24 +000011070void Sema::CheckDelegatingCtorCycles() {
11071 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11072
Alexis Hunt27a761d2011-05-04 23:29:54 +000011073 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11074 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000011075
Douglas Gregorbae31202011-07-27 21:57:17 +000011076 for (DelegatingCtorDeclsType::iterator
11077 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000011078 E = DelegatingCtorDecls.end();
11079 I != E; ++I) {
11080 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000011081 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000011082
11083 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11084 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000011085}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011086
11087/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11088Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11089 // Implicitly declared functions (e.g. copy constructors) are
11090 // __host__ __device__
11091 if (D->isImplicit())
11092 return CFT_HostDevice;
11093
11094 if (D->hasAttr<CUDAGlobalAttr>())
11095 return CFT_Global;
11096
11097 if (D->hasAttr<CUDADeviceAttr>()) {
11098 if (D->hasAttr<CUDAHostAttr>())
11099 return CFT_HostDevice;
11100 else
11101 return CFT_Device;
11102 }
11103
11104 return CFT_Host;
11105}
11106
11107bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11108 CUDAFunctionTarget CalleeTarget) {
11109 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11110 // Callable from the device only."
11111 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11112 return true;
11113
11114 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11115 // Callable from the host only."
11116 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11117 // Callable from the host only."
11118 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11119 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11120 return true;
11121
11122 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11123 return true;
11124
11125 return false;
11126}