blob: 4e5e307be6142e9b3ca92ba8c71a43ec30a2cca7 [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"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000040#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000041#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner58258242008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattnerb0d38442008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 public:
Mike Stump11289f42009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000063
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 };
Chris Lattner58258242008-04-10 02:22:51 +000070
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000077 }
78
Chris Lattnerb0d38442008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000104 }
Chris Lattner58258242008-04-10 02:22:51 +0000105
Douglas Gregor8e12c382008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000108
Douglas Gregor97a9c812008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000117 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000118
John McCall7353c862013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0d49512012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner58258242008-04-10 02:22:51 +0000146}
147
Richard Smithb7151b92013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith938f40b2011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithf623c962012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000344
Anders Carlsson84613c42009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000346}
347
Douglas Gregor4d87df52008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump11289f42009-09-09 15:08:12 +0000353
John McCall48871652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000355
Anders Carlsson84613c42009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000357
Anders Carlsson84613c42009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000359}
360
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000403 }
404 }
405}
406
David Majnemer502b0ed2013-06-25 23:09:30 +0000407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410 if (!PVD->hasDefaultArg())
411 return false;
412 if (!PVD->hasInheritedDefaultArg())
413 return true;
414 }
415 return false;
416}
417
Craig Toppere4794282012-09-21 04:33:26 +0000418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000424 bool Invalid = false;
425
Chris Lattner199abbc2008-04-08 05:04:30 +0000426 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000427 // For non-template functions, default arguments can be added in
428 // later declarations of a function in the same
429 // scope. Declarations in different scopes have completely
430 // distinct sets of default arguments. That is, declarations in
431 // inner scopes do not acquire default arguments from
432 // declarations in outer scopes, and vice versa. In a given
433 // function declaration, all parameters subsequent to a
434 // parameter with a default argument shall have default
435 // arguments supplied in this or previous declarations. A
436 // default argument shall not be redefined by a later
437 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000438 //
439 // C++ [dcl.fct.default]p6:
440 // Except for member functions of class templates, the default arguments
441 // in a member function definition that appears outside of the class
442 // definition are added to the set of default arguments provided by the
443 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445 ParmVarDecl *OldParam = Old->getParamDecl(p);
446 ParmVarDecl *NewParam = New->getParamDecl(p);
447
James Molloye9430032012-03-13 08:55:35 +0000448 bool OldParamHasDfl = OldParam->hasDefaultArg();
449 bool NewParamHasDfl = NewParam->hasDefaultArg();
450
451 NamedDecl *ND = Old;
452 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
453 // Ignore default parameters of old decl if they are not in
454 // the same scope.
455 OldParamHasDfl = false;
456
457 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000458
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000459 unsigned DiagDefaultParamID =
460 diag::err_param_default_argument_redefinition;
461
462 // MSVC accepts that default parameters be redefined for member functions
463 // of template class. The new default parameter's value is ignored.
464 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000465 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000466 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
467 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000468 // Merge the old default argument into the new parameter.
469 NewParam->setHasInheritedDefaultArg();
470 if (OldParam->hasUninstantiatedDefaultArg())
471 NewParam->setUninstantiatedDefaultArg(
472 OldParam->getUninstantiatedDefaultArg());
473 else
474 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000475 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000476 Invalid = false;
477 }
478 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000479
Francois Pichet8cb243a2011-04-10 04:58:30 +0000480 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
481 // hint here. Alternatively, we could walk the type-source information
482 // for NewParam to find the last source location in the type... but it
483 // isn't worth the effort right now. This is the kind of test case that
484 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000485 // int f(int);
486 // void g(int (*fp)(int) = f);
487 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000488 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000489 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000490
491 // Look for the function declaration where the default argument was
492 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000493 for (FunctionDecl *Older = Old->getPreviousDecl();
494 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495 if (!Older->getParamDecl(p)->hasDefaultArg())
496 break;
497
498 OldParam = Older->getParamDecl(p);
499 }
500
501 Diag(OldParam->getLocation(), diag::note_previous_definition)
502 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000503 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000504 // Merge the old default argument into the new parameter.
505 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000506 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000507 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000508 if (OldParam->hasUninstantiatedDefaultArg())
509 NewParam->setUninstantiatedDefaultArg(
510 OldParam->getUninstantiatedDefaultArg());
511 else
John McCalle61b02b2010-05-04 01:53:42 +0000512 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000513 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000514 if (New->getDescribedFunctionTemplate()) {
515 // Paragraph 4, quoted above, only applies to non-template functions.
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_template_redecl)
518 << NewParam->getDefaultArgRange();
519 Diag(Old->getLocation(), diag::note_template_prev_declaration)
520 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000521 } else if (New->getTemplateSpecializationKind()
522 != TSK_ImplicitInstantiation &&
523 New->getTemplateSpecializationKind() != TSK_Undeclared) {
524 // C++ [temp.expr.spec]p21:
525 // Default function arguments shall not be specified in a declaration
526 // or a definition for one of the following explicit specializations:
527 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000528 // - the explicit specialization of a member function template;
529 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000530 // template where the class template specialization to which the
531 // member function specialization belongs is implicitly
532 // instantiated.
533 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
534 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
535 << New->getDeclName()
536 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000537 } else if (New->getDeclContext()->isDependentContext()) {
538 // C++ [dcl.fct.default]p6 (DR217):
539 // Default arguments for a member function of a class template shall
540 // be specified on the initial declaration of the member function
541 // within the class template.
542 //
543 // Reading the tea leaves a bit in DR217 and its reference to DR205
544 // leads me to the conclusion that one cannot add default function
545 // arguments for an out-of-line definition of a member function of a
546 // dependent type.
547 int WhichKind = 2;
548 if (CXXRecordDecl *Record
549 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
550 if (Record->getDescribedClassTemplate())
551 WhichKind = 0;
552 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
553 WhichKind = 1;
554 else
555 WhichKind = 2;
556 }
557
558 Diag(NewParam->getLocation(),
559 diag::err_param_default_argument_member_template_redecl)
560 << WhichKind
561 << NewParam->getDefaultArgRange();
562 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000563 }
564 }
565
Richard Smith58c3cc12012-11-28 03:45:24 +0000566 // DR1344: If a default argument is added outside a class definition and that
567 // default argument makes the function a special member function, the program
568 // is ill-formed. This can only happen for constructors.
569 if (isa<CXXConstructorDecl>(New) &&
570 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
571 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
572 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
573 if (NewSM != OldSM) {
574 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
575 assert(NewParam->hasDefaultArg());
576 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
577 << NewParam->getDefaultArgRange() << NewSM;
578 Diag(Old->getLocation(), diag::note_previous_declaration);
579 }
580 }
581
Richard Smith5b8b3db2012-02-20 23:28:05 +0000582 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000583 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000584 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000585 if (New->isConstexpr() != Old->isConstexpr()) {
586 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
587 << New << New->isConstexpr();
588 Diag(Old->getLocation(), diag::note_previous_declaration);
589 Invalid = true;
590 }
591
David Majnemer502b0ed2013-06-25 23:09:30 +0000592 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
593 // argument expression, that declaration shall be a definition and shall be
594 // the only declaration of the function or function template in the
595 // translation unit.
596 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
597 functionDeclHasDefaultArgument(Old)) {
598 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
599 Diag(Old->getLocation(), diag::note_previous_declaration);
600 Invalid = true;
601 }
602
Douglas Gregorf40863c2010-02-12 07:32:17 +0000603 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000604 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000605
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000606 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000607}
608
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000609/// \brief Merge the exception specifications of two variable declarations.
610///
611/// This is called when there's a redeclaration of a VarDecl. The function
612/// checks if the redeclaration might have an exception specification and
613/// validates compatibility and merges the specs if necessary.
614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
615 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000616 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000617 return;
618
619 assert(Context.hasSameType(New->getType(), Old->getType()) &&
620 "Should only be called if types are otherwise the same.");
621
622 QualType NewType = New->getType();
623 QualType OldType = Old->getType();
624
625 // We're only interested in pointers and references to functions, as well
626 // as pointers to member functions.
627 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
628 NewType = R->getPointeeType();
629 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
630 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
631 NewType = P->getPointeeType();
632 OldType = OldType->getAs<PointerType>()->getPointeeType();
633 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
634 NewType = M->getPointeeType();
635 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
636 }
637
638 if (!NewType->isFunctionProtoType())
639 return;
640
641 // There's lots of special cases for functions. For function pointers, system
642 // libraries are hopefully not as broken so that we don't need these
643 // workarounds.
644 if (CheckEquivalentExceptionSpec(
645 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
646 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
647 New->setInvalidDecl();
648 }
649}
650
Chris Lattner199abbc2008-04-08 05:04:30 +0000651/// CheckCXXDefaultArguments - Verify that the default arguments for a
652/// function declaration are well-formed according to C++
653/// [dcl.fct.default].
654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
655 unsigned NumParams = FD->getNumParams();
656 unsigned p;
657
658 // Find first parameter with a default argument
659 for (p = 0; p < NumParams; ++p) {
660 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000661 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000662 break;
663 }
664
665 // C++ [dcl.fct.default]p4:
666 // In a given function declaration, all parameters
667 // subsequent to a parameter with a default argument shall
668 // have default arguments supplied in this or previous
669 // declarations. A default argument shall not be redefined
670 // by a later declaration (not even to the same value).
671 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000672 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000674 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000675 if (Param->isInvalidDecl())
676 /* We already complained about this parameter. */;
677 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000678 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000679 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000680 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000681 else
Mike Stump11289f42009-09-09 15:08:12 +0000682 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000683 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattner199abbc2008-04-08 05:04:30 +0000685 LastMissingDefaultArg = p;
686 }
687 }
688
689 if (LastMissingDefaultArg > 0) {
690 // Some default arguments were missing. Clear out all of the
691 // default arguments up to (and including) the last missing
692 // default argument, so that we leave the function parameters
693 // in a semantically valid state.
694 for (p = 0; p <= LastMissingDefaultArg; ++p) {
695 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000696 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000697 Param->setDefaultArg(0);
698 }
699 }
700 }
701}
Douglas Gregor556877c2008-04-13 21:30:24 +0000702
Richard Smitheb3c10c2011-10-01 02:31:28 +0000703// CheckConstexprParameterTypes - Check whether a function's parameter types
704// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000705// diagnostic and return false.
706static bool CheckConstexprParameterTypes(Sema &SemaRef,
707 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000708 unsigned ArgIndex = 0;
709 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
710 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
711 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
712 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
713 SourceLocation ParamLoc = PD->getLocation();
714 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000715 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000716 diag::err_constexpr_non_literal_param,
717 ArgIndex+1, PD->getSourceRange(),
718 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000719 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000720 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000721 return true;
722}
723
724/// \brief Get diagnostic %select index for tag kind for
725/// record diagnostic message.
726/// WARNING: Indexes apply to particular diagnostics only!
727///
728/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000730 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000731 case TTK_Struct: return 0;
732 case TTK_Interface: return 1;
733 case TTK_Class: return 2;
734 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000735 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000736}
737
738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
739// the requirements of a constexpr function definition or a constexpr
740// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000741// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000742//
Richard Smith3607ffe2012-02-13 03:54:03 +0000743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000745 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
746 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000747 // C++11 [dcl.constexpr]p4:
748 // The definition of a constexpr constructor shall satisfy the following
749 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000750 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000751 const CXXRecordDecl *RD = MD->getParent();
752 if (RD->getNumVBases()) {
753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
754 << isa<CXXConstructorDecl>(NewFD)
755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
756 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
757 E = RD->vbases_end(); I != E; ++I)
758 Diag(I->getLocStart(),
Richard Smith3607ffe2012-02-13 03:54:03 +0000759 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000760 return false;
761 }
Richard Smith7971b692012-01-13 04:54:00 +0000762 }
763
764 if (!isa<CXXConstructorDecl>(NewFD)) {
765 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000766 // The definition of a constexpr function shall satisfy the following
767 // constraints:
768 // - it shall not be virtual;
769 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
770 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000771 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000772
Richard Smith3607ffe2012-02-13 03:54:03 +0000773 // If it's not obvious why this function is virtual, find an overridden
774 // function which uses the 'virtual' keyword.
775 const CXXMethodDecl *WrittenVirtual = Method;
776 while (!WrittenVirtual->isVirtualAsWritten())
777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
778 if (WrittenVirtual != Method)
779 Diag(WrittenVirtual->getLocation(),
780 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 return false;
782 }
783
784 // - its return type shall be a literal type;
785 QualType RT = NewFD->getResultType();
786 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000787 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000788 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000789 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000790 }
791
Richard Smith7971b692012-01-13 04:54:00 +0000792 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000793 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000794 return false;
795
Richard Smitheb3c10c2011-10-01 02:31:28 +0000796 return true;
797}
798
799/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801///
Richard Smithd9f663b2013-04-22 15:31:51 +0000802/// \return true if the body is OK (maybe only as an extension), false if we
803/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000805 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
806 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000807 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
808 // contain only
809 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
810 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
811 switch ((*DclIt)->getKind()) {
812 case Decl::StaticAssert:
813 case Decl::Using:
814 case Decl::UsingShadow:
815 case Decl::UsingDirective:
816 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000817 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000818 // - static_assert-declarations
819 // - using-declarations,
820 // - using-directives,
821 continue;
822
823 case Decl::Typedef:
824 case Decl::TypeAlias: {
825 // - typedef declarations and alias-declarations that do not define
826 // classes or enumerations,
827 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
828 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
829 // Don't allow variably-modified types in constexpr functions.
830 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
831 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
832 << TL.getSourceRange() << TL.getType()
833 << isa<CXXConstructorDecl>(Dcl);
834 return false;
835 }
836 continue;
837 }
838
839 case Decl::Enum:
840 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000841 // C++1y allows types to be defined, not just declared.
842 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
843 SemaRef.Diag(DS->getLocStart(),
844 SemaRef.getLangOpts().CPlusPlus1y
845 ? diag::warn_cxx11_compat_constexpr_type_definition
846 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000847 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000848 continue;
849
Richard Smithd9f663b2013-04-22 15:31:51 +0000850 case Decl::EnumConstant:
851 case Decl::IndirectField:
852 case Decl::ParmVar:
853 // These can only appear with other declarations which are banned in
854 // C++11 and permitted in C++1y, so ignore them.
855 continue;
856
857 case Decl::Var: {
858 // C++1y [dcl.constexpr]p3 allows anything except:
859 // a definition of a variable of non-literal type or of static or
860 // thread storage duration or for which no initialization is performed.
861 VarDecl *VD = cast<VarDecl>(*DclIt);
862 if (VD->isThisDeclarationADefinition()) {
863 if (VD->isStaticLocal()) {
864 SemaRef.Diag(VD->getLocation(),
865 diag::err_constexpr_local_var_static)
866 << isa<CXXConstructorDecl>(Dcl)
867 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
868 return false;
869 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000870 if (!VD->getType()->isDependentType() &&
871 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000872 VD->getLocation(), VD->getType(),
873 diag::err_constexpr_local_var_non_literal_type,
874 isa<CXXConstructorDecl>(Dcl)))
875 return false;
876 if (!VD->hasInit()) {
877 SemaRef.Diag(VD->getLocation(),
878 diag::err_constexpr_local_var_no_init)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883 SemaRef.Diag(VD->getLocation(),
884 SemaRef.getLangOpts().CPlusPlus1y
885 ? diag::warn_cxx11_compat_constexpr_local_var
886 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000887 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000888 continue;
889 }
890
891 case Decl::NamespaceAlias:
892 case Decl::Function:
893 // These are disallowed in C++11 and permitted in C++1y. Allow them
894 // everywhere as an extension.
895 if (!Cxx1yLoc.isValid())
896 Cxx1yLoc = DS->getLocStart();
897 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000898
899 default:
900 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904 }
905
906 return true;
907}
908
909/// Check that the given field is initialized within a constexpr constructor.
910///
911/// \param Dcl The constexpr constructor being checked.
912/// \param Field The field being checked. This may be a member of an anonymous
913/// struct or union nested within the class being checked.
914/// \param Inits All declarations, including anonymous struct/union members and
915/// indirect members, for which any initialization was provided.
916/// \param Diagnosed Set to true if an error is produced.
917static void CheckConstexprCtorInitializer(Sema &SemaRef,
918 const FunctionDecl *Dcl,
919 FieldDecl *Field,
920 llvm::SmallSet<Decl*, 16> &Inits,
921 bool &Diagnosed) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000922 if (Field->isUnnamedBitfield())
923 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000924
925 if (Field->isAnonymousStructOrUnion() &&
926 Field->getType()->getAsCXXRecordDecl()->isEmpty())
927 return;
928
Richard Smitheb3c10c2011-10-01 02:31:28 +0000929 if (!Inits.count(Field)) {
930 if (!Diagnosed) {
931 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
932 Diagnosed = true;
933 }
934 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
935 } else if (Field->isAnonymousStructOrUnion()) {
936 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
937 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
938 I != E; ++I)
939 // If an anonymous union contains an anonymous struct of which any member
940 // is initialized, all members must be initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000941 if (!RD->isUnion() || Inits.count(*I))
942 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000943 }
944}
945
Richard Smithd9f663b2013-04-22 15:31:51 +0000946/// Check the provided statement is allowed in a constexpr function
947/// definition.
948static bool
949CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
950 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
951 SourceLocation &Cxx1yLoc) {
952 // - its function-body shall be [...] a compound-statement that contains only
953 switch (S->getStmtClass()) {
954 case Stmt::NullStmtClass:
955 // - null statements,
956 return true;
957
958 case Stmt::DeclStmtClass:
959 // - static_assert-declarations
960 // - using-declarations,
961 // - using-directives,
962 // - typedef declarations and alias-declarations that do not define
963 // classes or enumerations,
964 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
965 return false;
966 return true;
967
968 case Stmt::ReturnStmtClass:
969 // - and exactly one return statement;
970 if (isa<CXXConstructorDecl>(Dcl)) {
971 // C++1y allows return statements in constexpr constructors.
972 if (!Cxx1yLoc.isValid())
973 Cxx1yLoc = S->getLocStart();
974 return true;
975 }
976
977 ReturnStmts.push_back(S->getLocStart());
978 return true;
979
980 case Stmt::CompoundStmtClass: {
981 // C++1y allows compound-statements.
982 if (!Cxx1yLoc.isValid())
983 Cxx1yLoc = S->getLocStart();
984
985 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
986 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
987 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
988 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 }
992 return true;
993 }
994
995 case Stmt::AttributedStmtClass:
996 if (!Cxx1yLoc.isValid())
997 Cxx1yLoc = S->getLocStart();
998 return true;
999
1000 case Stmt::IfStmtClass: {
1001 // C++1y allows if-statements.
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004
1005 IfStmt *If = cast<IfStmt>(S);
1006 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1007 Cxx1yLoc))
1008 return false;
1009 if (If->getElse() &&
1010 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1011 Cxx1yLoc))
1012 return false;
1013 return true;
1014 }
1015
1016 case Stmt::WhileStmtClass:
1017 case Stmt::DoStmtClass:
1018 case Stmt::ForStmtClass:
1019 case Stmt::CXXForRangeStmtClass:
1020 case Stmt::ContinueStmtClass:
1021 // C++1y allows all of these. We don't allow them as extensions in C++11,
1022 // because they don't make sense without variable mutation.
1023 if (!SemaRef.getLangOpts().CPlusPlus1y)
1024 break;
1025 if (!Cxx1yLoc.isValid())
1026 Cxx1yLoc = S->getLocStart();
1027 for (Stmt::child_range Children = S->children(); Children; ++Children)
1028 if (*Children &&
1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1030 Cxx1yLoc))
1031 return false;
1032 return true;
1033
1034 case Stmt::SwitchStmtClass:
1035 case Stmt::CaseStmtClass:
1036 case Stmt::DefaultStmtClass:
1037 case Stmt::BreakStmtClass:
1038 // C++1y allows switch-statements, and since they don't need variable
1039 // mutation, we can reasonably allow them in C++11 as an extension.
1040 if (!Cxx1yLoc.isValid())
1041 Cxx1yLoc = S->getLocStart();
1042 for (Stmt::child_range Children = S->children(); Children; ++Children)
1043 if (*Children &&
1044 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1045 Cxx1yLoc))
1046 return false;
1047 return true;
1048
1049 default:
1050 if (!isa<Expr>(S))
1051 break;
1052
1053 // C++1y allows expression-statements.
1054 if (!Cxx1yLoc.isValid())
1055 Cxx1yLoc = S->getLocStart();
1056 return true;
1057 }
1058
1059 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1060 << isa<CXXConstructorDecl>(Dcl);
1061 return false;
1062}
1063
Richard Smitheb3c10c2011-10-01 02:31:28 +00001064/// Check the body for the given constexpr function declaration only contains
1065/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1066///
1067/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001068bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001069 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001070 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001071 // The definition of a constexpr function shall satisfy the following
1072 // constraints: [...]
1073 // - its function-body shall be = delete, = default, or a
1074 // compound-statement
1075 //
Richard Smith74388b42012-02-04 00:33:54 +00001076 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001077 // In the definition of a constexpr constructor, [...]
1078 // - its function-body shall not be a function-try-block;
1079 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1080 << isa<CXXConstructorDecl>(Dcl);
1081 return false;
1082 }
1083
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001084 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001085
1086 // - its function-body shall be [...] a compound-statement that contains only
1087 // [... list of cases ...]
1088 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1089 SourceLocation Cxx1yLoc;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1091 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001092 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1093 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001094 }
1095
Richard Smithd9f663b2013-04-22 15:31:51 +00001096 if (Cxx1yLoc.isValid())
1097 Diag(Cxx1yLoc,
1098 getLangOpts().CPlusPlus1y
1099 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1100 : diag::ext_constexpr_body_invalid_stmt)
1101 << isa<CXXConstructorDecl>(Dcl);
1102
Richard Smitheb3c10c2011-10-01 02:31:28 +00001103 if (const CXXConstructorDecl *Constructor
1104 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1105 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001106 // DR1359:
1107 // - every non-variant non-static data member and base class sub-object
1108 // shall be initialized;
1109 // - if the class is a non-empty union, or for each non-empty anonymous
1110 // union member of a non-union class, exactly one non-static data member
1111 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001112 if (RD->isUnion()) {
Richard Smith4d59eeb2012-02-09 06:40:58 +00001113 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001114 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1115 return false;
1116 }
Richard Smithf368fb42011-10-10 16:38:04 +00001117 } else if (!Constructor->isDependentContext() &&
1118 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001119 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1120
1121 // Skip detailed checking if we have enough initializers, and we would
1122 // allow at most one initializer per member.
1123 bool AnyAnonStructUnionMembers = false;
1124 unsigned Fields = 0;
1125 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1126 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001127 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001128 AnyAnonStructUnionMembers = true;
1129 break;
1130 }
1131 }
1132 if (AnyAnonStructUnionMembers ||
1133 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1134 // Check initialization of non-static data members. Base classes are
1135 // always initialized so do not need to be checked. Dependent bases
1136 // might not have initializers in the member initializer list.
1137 llvm::SmallSet<Decl*, 16> Inits;
1138 for (CXXConstructorDecl::init_const_iterator
1139 I = Constructor->init_begin(), E = Constructor->init_end();
1140 I != E; ++I) {
1141 if (FieldDecl *FD = (*I)->getMember())
1142 Inits.insert(FD);
1143 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1144 Inits.insert(ID->chain_begin(), ID->chain_end());
1145 }
1146
1147 bool Diagnosed = false;
1148 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1149 E = RD->field_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001150 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001151 if (Diagnosed)
1152 return false;
1153 }
1154 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 } else {
1156 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001157 // C++1y doesn't require constexpr functions to contain a 'return'
1158 // statement. We still do, unless the return type is void, because
1159 // otherwise if there's no return statement, the function cannot
1160 // be used in a core constant expression.
Richard Smith3da88fa2013-04-26 14:36:30 +00001161 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001162 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001163 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1164 : diag::err_constexpr_body_no_return);
1165 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001166 }
1167 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001168 Diag(ReturnStmts.back(),
1169 getLangOpts().CPlusPlus1y
1170 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1171 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001172 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1173 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001174 }
1175 }
1176
Richard Smith74388b42012-02-04 00:33:54 +00001177 // C++11 [dcl.constexpr]p5:
1178 // if no function argument values exist such that the function invocation
1179 // substitution would produce a constant expression, the program is
1180 // ill-formed; no diagnostic required.
1181 // C++11 [dcl.constexpr]p3:
1182 // - every constructor call and implicit conversion used in initializing the
1183 // return value shall be one of those allowed in a constant expression.
1184 // C++11 [dcl.constexpr]p4:
1185 // - every constructor involved in initializing non-static data members and
1186 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001187 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001188 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001189 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001190 << isa<CXXConstructorDecl>(Dcl);
1191 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1192 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001193 // Don't return false here: we allow this for compatibility in
1194 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001195 }
1196
Richard Smitheb3c10c2011-10-01 02:31:28 +00001197 return true;
1198}
1199
Douglas Gregor61956c42008-10-31 09:07:45 +00001200/// isCurrentClassName - Determine whether the identifier II is the
1201/// name of the class type currently being defined. In the case of
1202/// nested classes, this will only return true if II is the name of
1203/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001204bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1205 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001206 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001207
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001208 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001209 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001210 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001211 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1212 } else
1213 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1214
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001215 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001216 return &II == CurDecl->getIdentifier();
1217 else
1218 return false;
1219}
1220
Douglas Gregordc974572012-11-10 07:24:09 +00001221/// \brief Determine whether the given class is a base class of the given
1222/// class, including looking at dependent bases.
1223static bool findCircularInheritance(const CXXRecordDecl *Class,
1224 const CXXRecordDecl *Current) {
1225 SmallVector<const CXXRecordDecl*, 8> Queue;
1226
1227 Class = Class->getCanonicalDecl();
1228 while (true) {
1229 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1230 E = Current->bases_end();
1231 I != E; ++I) {
1232 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1233 if (!Base)
1234 continue;
1235
1236 Base = Base->getDefinition();
1237 if (!Base)
1238 continue;
1239
1240 if (Base->getCanonicalDecl() == Class)
1241 return true;
1242
1243 Queue.push_back(Base);
1244 }
1245
1246 if (Queue.empty())
1247 return false;
1248
1249 Current = Queue.back();
1250 Queue.pop_back();
1251 }
1252
1253 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001254}
1255
Mike Stump11289f42009-09-09 15:08:12 +00001256/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001257///
1258/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1259/// and returns NULL otherwise.
1260CXXBaseSpecifier *
1261Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1262 SourceRange SpecifierRange,
1263 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001264 TypeSourceInfo *TInfo,
1265 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001266 QualType BaseType = TInfo->getType();
1267
Douglas Gregor463421d2009-03-03 04:44:36 +00001268 // C++ [class.union]p1:
1269 // A union shall not have base classes.
1270 if (Class->isUnion()) {
1271 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1272 << SpecifierRange;
1273 return 0;
1274 }
1275
Douglas Gregor752a5952011-01-03 22:36:02 +00001276 if (EllipsisLoc.isValid() &&
1277 !TInfo->getType()->containsUnexpandedParameterPack()) {
1278 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1279 << TInfo->getTypeLoc().getSourceRange();
1280 EllipsisLoc = SourceLocation();
1281 }
Douglas Gregor62004702012-11-10 01:18:17 +00001282
1283 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1284
1285 if (BaseType->isDependentType()) {
1286 // Make sure that we don't have circular inheritance among our dependent
1287 // bases. For non-dependent bases, the check for completeness below handles
1288 // this.
1289 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1290 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1291 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001292 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001293 Diag(BaseLoc, diag::err_circular_inheritance)
1294 << BaseType << Context.getTypeDeclType(Class);
1295
1296 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1297 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1298 << BaseType;
1299
1300 return 0;
1301 }
1302 }
1303
Mike Stump11289f42009-09-09 15:08:12 +00001304 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001305 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001306 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001307 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001308
1309 // Base specifiers must be record types.
1310 if (!BaseType->isRecordType()) {
1311 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1312 return 0;
1313 }
1314
1315 // C++ [class.union]p1:
1316 // A union shall not be used as a base class.
1317 if (BaseType->isUnionType()) {
1318 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1319 return 0;
1320 }
1321
1322 // C++ [class.derived]p2:
1323 // The class-name in a base-specifier shall not be an incompletely
1324 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001325 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001326 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001327 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001328 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001329 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001330
Eli Friedmanc96d4962009-08-15 21:55:26 +00001331 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001332 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001333 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001334 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001335 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001336 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001337 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001338
Anders Carlsson65c76d32011-03-25 14:55:14 +00001339 // C++ [class]p3:
1340 // If a class is marked final and it appears as a base-type-specifier in
1341 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001342 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001343 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1344 << CXXBaseDecl->getDeclName();
1345 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1346 << CXXBaseDecl->getDeclName();
1347 return 0;
1348 }
1349
John McCall3696dcb2010-08-17 07:23:57 +00001350 if (BaseDecl->isInvalidDecl())
1351 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001352
1353 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001354 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001355 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001356 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001357}
1358
Douglas Gregor556877c2008-04-13 21:30:24 +00001359/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1360/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001361/// example:
1362/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001363/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001364BaseResult
John McCall48871652010-08-21 09:40:31 +00001365Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001366 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001367 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001368 ParsedType basetype, SourceLocation BaseLoc,
1369 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001370 if (!classdecl)
1371 return true;
1372
Douglas Gregorc40290e2009-03-09 23:48:35 +00001373 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001374 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001375 if (!Class)
1376 return true;
1377
Richard Smith4c96e992013-02-19 23:47:15 +00001378 // We do not support any C++11 attributes on base-specifiers yet.
1379 // Diagnose any attributes we see.
1380 if (!Attributes.empty()) {
1381 for (AttributeList *Attr = Attributes.getList(); Attr;
1382 Attr = Attr->getNext()) {
1383 if (Attr->isInvalid() ||
1384 Attr->getKind() == AttributeList::IgnoredAttribute)
1385 continue;
1386 Diag(Attr->getLoc(),
1387 Attr->getKind() == AttributeList::UnknownAttribute
1388 ? diag::warn_unknown_attribute_ignored
1389 : diag::err_base_specifier_attribute)
1390 << Attr->getName();
1391 }
1392 }
1393
Nick Lewycky19b9f952010-07-26 16:56:01 +00001394 TypeSourceInfo *TInfo = 0;
1395 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001396
Douglas Gregor752a5952011-01-03 22:36:02 +00001397 if (EllipsisLoc.isInvalid() &&
1398 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001399 UPPC_BaseType))
1400 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001401
Douglas Gregor463421d2009-03-03 04:44:36 +00001402 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001403 Virtual, Access, TInfo,
1404 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001405 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001406 else
1407 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregor463421d2009-03-03 04:44:36 +00001409 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001410}
Douglas Gregor556877c2008-04-13 21:30:24 +00001411
Douglas Gregor463421d2009-03-03 04:44:36 +00001412/// \brief Performs the actual work of attaching the given base class
1413/// specifiers to a C++ class.
1414bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1415 unsigned NumBases) {
1416 if (NumBases == 0)
1417 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001418
1419 // Used to keep track of which base types we have already seen, so
1420 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001421 // that the key is always the unqualified canonical type of the base
1422 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001423 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1424
1425 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001426 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001427 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001428 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001429 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001430 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001431 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001432
1433 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1434 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001435 // C++ [class.mi]p3:
1436 // A class shall not be specified as a direct base class of a
1437 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001438 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001439 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001440 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001441 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001442
1443 // Delete the duplicate base class specifier; we're going to
1444 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001445 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001446
1447 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001448 } else {
1449 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001450 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001451 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001452 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1453 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1454 if (Class->isInterface() &&
1455 (!RD->isInterface() ||
1456 KnownBase->getAccessSpecifier() != AS_public)) {
1457 // The Microsoft extension __interface does not permit bases that
1458 // are not themselves public interfaces.
1459 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1460 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1461 << RD->getSourceRange();
1462 Invalid = true;
1463 }
1464 if (RD->hasAttr<WeakAttr>())
1465 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1466 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001467 }
1468 }
1469
1470 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001471 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001472
1473 // Delete the remaining (good) base class specifiers, since their
1474 // data has been copied into the CXXRecordDecl.
1475 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001476 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001477
1478 return Invalid;
1479}
1480
1481/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1482/// class, after checking whether there are any duplicate base
1483/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001484void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001485 unsigned NumBases) {
1486 if (!ClassDecl || !Bases || !NumBases)
1487 return;
1488
1489 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001490 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001491 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001492}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001493
Douglas Gregor36d1b142009-10-06 17:59:45 +00001494/// \brief Determine whether the type \p Derived is a C++ class that is
1495/// derived from the type \p Base.
1496bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001497 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001498 return false;
John McCalle78aac42010-03-10 03:28:59 +00001499
Douglas Gregor45bb4832013-03-26 23:36:30 +00001500 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001501 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001502 return false;
1503
Douglas Gregor45bb4832013-03-26 23:36:30 +00001504 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001505 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001506 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001507
1508 // If either the base or the derived type is invalid, don't try to
1509 // check whether one is derived from the other.
1510 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1511 return false;
1512
John McCall67da35c2010-02-04 22:26:26 +00001513 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1514 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001515}
1516
1517/// \brief Determine whether the type \p Derived is a C++ class that is
1518/// derived from the type \p Base.
1519bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001520 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001521 return false;
1522
Douglas Gregor45bb4832013-03-26 23:36:30 +00001523 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001524 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001525 return false;
1526
Douglas Gregor45bb4832013-03-26 23:36:30 +00001527 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001528 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001529 return false;
1530
Douglas Gregor36d1b142009-10-06 17:59:45 +00001531 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1532}
1533
Anders Carlssona70cff62010-04-24 19:06:50 +00001534void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001535 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001536 assert(BasePathArray.empty() && "Base path array must be empty!");
1537 assert(Paths.isRecordingPaths() && "Must record paths!");
1538
1539 const CXXBasePath &Path = Paths.front();
1540
1541 // We first go backward and check if we have a virtual base.
1542 // FIXME: It would be better if CXXBasePath had the base specifier for
1543 // the nearest virtual base.
1544 unsigned Start = 0;
1545 for (unsigned I = Path.size(); I != 0; --I) {
1546 if (Path[I - 1].Base->isVirtual()) {
1547 Start = I - 1;
1548 break;
1549 }
1550 }
1551
1552 // Now add all bases.
1553 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001554 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001555}
1556
Douglas Gregor88d292c2010-05-13 16:44:06 +00001557/// \brief Determine whether the given base path includes a virtual
1558/// base class.
John McCallcf142162010-08-07 06:22:56 +00001559bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1560 for (CXXCastPath::const_iterator B = BasePath.begin(),
1561 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001562 B != BEnd; ++B)
1563 if ((*B)->isVirtual())
1564 return true;
1565
1566 return false;
1567}
1568
Douglas Gregor36d1b142009-10-06 17:59:45 +00001569/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1570/// conversion (where Derived and Base are class types) is
1571/// well-formed, meaning that the conversion is unambiguous (and
1572/// that all of the base classes are accessible). Returns true
1573/// and emits a diagnostic if the code is ill-formed, returns false
1574/// otherwise. Loc is the location where this routine should point to
1575/// if there is an error, and Range is the source range to highlight
1576/// if there is an error.
1577bool
1578Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001579 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001580 unsigned AmbigiousBaseConvID,
1581 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001582 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001583 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001584 // First, determine whether the path from Derived to Base is
1585 // ambiguous. This is slightly more expensive than checking whether
1586 // the Derived to Base conversion exists, because here we need to
1587 // explore multiple paths to determine if there is an ambiguity.
1588 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1589 /*DetectVirtual=*/false);
1590 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1591 assert(DerivationOkay &&
1592 "Can only be used with a derived-to-base conversion");
1593 (void)DerivationOkay;
1594
1595 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001596 if (InaccessibleBaseID) {
1597 // Check that the base class can be accessed.
1598 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1599 InaccessibleBaseID)) {
1600 case AR_inaccessible:
1601 return true;
1602 case AR_accessible:
1603 case AR_dependent:
1604 case AR_delayed:
1605 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001606 }
John McCall5b0829a2010-02-10 09:31:12 +00001607 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001608
1609 // Build a base path if necessary.
1610 if (BasePath)
1611 BuildBasePathArray(Paths, *BasePath);
1612 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001613 }
1614
David Majnemer626032f2013-06-22 06:43:58 +00001615 if (AmbigiousBaseConvID) {
1616 // We know that the derived-to-base conversion is ambiguous, and
1617 // we're going to produce a diagnostic. Perform the derived-to-base
1618 // search just one more time to compute all of the possible paths so
1619 // that we can print them out. This is more expensive than any of
1620 // the previous derived-to-base checks we've done, but at this point
1621 // performance isn't as much of an issue.
1622 Paths.clear();
1623 Paths.setRecordingPaths(true);
1624 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1625 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1626 (void)StillOkay;
1627
1628 // Build up a textual representation of the ambiguous paths, e.g.,
1629 // D -> B -> A, that will be used to illustrate the ambiguous
1630 // conversions in the diagnostic. We only print one of the paths
1631 // to each base class subobject.
1632 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1633
1634 Diag(Loc, AmbigiousBaseConvID)
1635 << Derived << Base << PathDisplayStr << Range << Name;
1636 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001637 return true;
1638}
1639
1640bool
1641Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001642 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001643 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001644 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001645 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001646 IgnoreAccess ? 0
1647 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001648 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001649 Loc, Range, DeclarationName(),
1650 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001651}
1652
1653
1654/// @brief Builds a string representing ambiguous paths from a
1655/// specific derived class to different subobjects of the same base
1656/// class.
1657///
1658/// This function builds a string that can be used in error messages
1659/// to show the different paths that one can take through the
1660/// inheritance hierarchy to go from the derived class to different
1661/// subobjects of a base class. The result looks something like this:
1662/// @code
1663/// struct D -> struct B -> struct A
1664/// struct D -> struct C -> struct A
1665/// @endcode
1666std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1667 std::string PathDisplayStr;
1668 std::set<unsigned> DisplayedPaths;
1669 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1670 Path != Paths.end(); ++Path) {
1671 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1672 // We haven't displayed a path to this particular base
1673 // class subobject yet.
1674 PathDisplayStr += "\n ";
1675 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1676 for (CXXBasePath::const_iterator Element = Path->begin();
1677 Element != Path->end(); ++Element)
1678 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1679 }
1680 }
1681
1682 return PathDisplayStr;
1683}
1684
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001685//===----------------------------------------------------------------------===//
1686// C++ class member Handling
1687//===----------------------------------------------------------------------===//
1688
Abramo Bagnarad7340582010-06-05 05:09:32 +00001689/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001690bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1691 SourceLocation ASLoc,
1692 SourceLocation ColonLoc,
1693 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001694 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001695 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001696 ASLoc, ColonLoc);
1697 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001698 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001699}
1700
Richard Smith18f07db2012-08-06 03:25:17 +00001701/// CheckOverrideControl - Check C++11 override control semantics.
1702void Sema::CheckOverrideControl(Decl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001703 if (D->isInvalidDecl())
1704 return;
1705
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001706 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001707
Richard Smith18f07db2012-08-06 03:25:17 +00001708 // Do we know which functions this declaration might be overriding?
1709 bool OverridesAreKnown = !MD ||
1710 (!MD->getParent()->hasAnyDependentBases() &&
1711 !MD->getType()->isDependentType());
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001712
Richard Smith18f07db2012-08-06 03:25:17 +00001713 if (!MD || !MD->isVirtual()) {
1714 if (OverridesAreKnown) {
1715 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1716 Diag(OA->getLocation(),
1717 diag::override_keyword_only_allowed_on_virtual_member_functions)
1718 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1719 D->dropAttr<OverrideAttr>();
1720 }
1721 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1722 Diag(FA->getLocation(),
1723 diag::override_keyword_only_allowed_on_virtual_member_functions)
1724 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1725 D->dropAttr<FinalAttr>();
1726 }
1727 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001728 return;
1729 }
Richard Smith18f07db2012-08-06 03:25:17 +00001730
1731 if (!OverridesAreKnown)
1732 return;
1733
1734 // C++11 [class.virtual]p5:
1735 // If a virtual function is marked with the virt-specifier override and
1736 // does not override a member function of a base class, the program is
1737 // ill-formed.
1738 bool HasOverriddenMethods =
1739 MD->begin_overridden_methods() != MD->end_overridden_methods();
1740 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1741 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1742 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001743}
1744
Richard Smith18f07db2012-08-06 03:25:17 +00001745/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001746/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001747/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001748bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1749 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001750 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001751 return false;
1752
1753 Diag(New->getLocation(), diag::err_final_function_overridden)
1754 << New->getDeclName();
1755 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1756 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001757}
1758
Daniel Jasper0baec5492012-06-06 08:32:04 +00001759static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001760 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1761 // FIXME: Destruction of ObjC lifetime types has side-effects.
1762 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1763 return !RD->isCompleteDefinition() ||
1764 !RD->hasTrivialDefaultConstructor() ||
1765 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001766 return false;
1767}
1768
John McCall5e77d762013-04-16 07:28:30 +00001769static AttributeList *getMSPropertyAttr(AttributeList *list) {
1770 for (AttributeList* it = list; it != 0; it = it->getNext())
1771 if (it->isDeclspecPropertyAttribute())
1772 return it;
1773 return 0;
1774}
1775
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001776/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1777/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001778/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001779/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1780/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001781NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001782Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001783 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001784 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001785 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001786 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001787 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1788 DeclarationName Name = NameInfo.getName();
1789 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001790
1791 // For anonymous bitfields, the location should point to the type.
1792 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001793 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001794
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001795 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001796
John McCallb1cd7da2010-06-04 08:34:12 +00001797 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001798 assert(!DS.isFriendSpecified());
1799
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001800 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001801
John McCalldb632ac2012-09-25 07:32:39 +00001802 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1803 // The Microsoft extension __interface only permits public member functions
1804 // and prohibits constructors, destructors, operators, non-public member
1805 // functions, static methods and data members.
1806 unsigned InvalidDecl;
1807 bool ShowDeclName = true;
1808 if (!isFunc)
1809 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1810 else if (AS != AS_public)
1811 InvalidDecl = 2;
1812 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1813 InvalidDecl = 3;
1814 else switch (Name.getNameKind()) {
1815 case DeclarationName::CXXConstructorName:
1816 InvalidDecl = 4;
1817 ShowDeclName = false;
1818 break;
1819
1820 case DeclarationName::CXXDestructorName:
1821 InvalidDecl = 5;
1822 ShowDeclName = false;
1823 break;
1824
1825 case DeclarationName::CXXOperatorName:
1826 case DeclarationName::CXXConversionFunctionName:
1827 InvalidDecl = 6;
1828 break;
1829
1830 default:
1831 InvalidDecl = 0;
1832 break;
1833 }
1834
1835 if (InvalidDecl) {
1836 if (ShowDeclName)
1837 Diag(Loc, diag::err_invalid_member_in_interface)
1838 << (InvalidDecl-1) << Name;
1839 else
1840 Diag(Loc, diag::err_invalid_member_in_interface)
1841 << (InvalidDecl-1) << "";
1842 return 0;
1843 }
1844 }
1845
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001846 // C++ 9.2p6: A member shall not be declared to have automatic storage
1847 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001848 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1849 // data members and cannot be applied to names declared const or static,
1850 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001851 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001852 case DeclSpec::SCS_unspecified:
1853 case DeclSpec::SCS_typedef:
1854 case DeclSpec::SCS_static:
1855 break;
1856 case DeclSpec::SCS_mutable:
1857 if (isFunc) {
1858 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001859
Richard Smithb4a9e862013-04-12 22:46:28 +00001860 // FIXME: It would be nicer if the keyword was ignored only for this
1861 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001862 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001863 }
1864 break;
1865 default:
1866 Diag(DS.getStorageClassSpecLoc(),
1867 diag::err_storageclass_invalid_for_member);
1868 D.getMutableDeclSpec().ClearStorageClassSpecs();
1869 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001870 }
1871
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001872 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1873 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001874 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001875
David Blaikie35506f82013-01-30 01:22:18 +00001876 if (DS.isConstexprSpecified() && isInstField) {
1877 SemaDiagnosticBuilder B =
1878 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1879 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1880 if (InitStyle == ICIS_NoInit) {
1881 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1882 D.getMutableDeclSpec().ClearConstexprSpec();
1883 const char *PrevSpec;
1884 unsigned DiagID;
1885 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1886 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001887 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001888 assert(!Failed && "Making a constexpr member const shouldn't fail");
1889 } else {
1890 B << 1;
1891 const char *PrevSpec;
1892 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001893 if (D.getMutableDeclSpec().SetStorageClassSpec(
1894 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001895 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001896 "This is the only DeclSpec that should fail to be applied");
1897 B << 1;
1898 } else {
1899 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1900 isInstField = false;
1901 }
1902 }
1903 }
1904
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001905 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001906 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001907 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001908
1909 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001910 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001911 Diag(Loc, diag::err_bad_variable_name)
1912 << Name;
1913 return 0;
1914 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001915
Benjamin Kramer365082d2012-05-19 16:34:46 +00001916 IdentifierInfo *II = Name.getAsIdentifierInfo();
1917
Douglas Gregor7c26c042011-09-21 14:40:46 +00001918 // Member field could not be with "template" keyword.
1919 // So TemplateParameterLists should be empty in this case.
1920 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001921 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00001922 if (TemplateParams->size()) {
1923 // There is no such thing as a member field template.
1924 Diag(D.getIdentifierLoc(), diag::err_template_member)
1925 << II
1926 << SourceRange(TemplateParams->getTemplateLoc(),
1927 TemplateParams->getRAngleLoc());
1928 } else {
1929 // There is an extraneous 'template<>' for this member.
1930 Diag(TemplateParams->getTemplateLoc(),
1931 diag::err_template_member_noparams)
1932 << II
1933 << SourceRange(TemplateParams->getTemplateLoc(),
1934 TemplateParams->getRAngleLoc());
1935 }
1936 return 0;
1937 }
1938
Douglas Gregora007d362010-10-13 22:19:53 +00001939 if (SS.isSet() && !SS.isInvalid()) {
1940 // The user provided a superfluous scope specifier inside a class
1941 // definition:
1942 //
1943 // class X {
1944 // int X::member;
1945 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001946 if (DeclContext *DC = computeDeclContext(SS, false))
1947 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00001948 else
1949 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1950 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001951
Douglas Gregora007d362010-10-13 22:19:53 +00001952 SS.clear();
1953 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001954
John McCall5e77d762013-04-16 07:28:30 +00001955 AttributeList *MSPropertyAttr =
1956 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1957 if (MSPropertyAttr) {
1958 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1959 BitWidth, InitStyle, AS, MSPropertyAttr);
1960 isInstField = false;
1961 } else {
1962 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1963 BitWidth, InitStyle, AS);
1964 }
Chris Lattner97e277e2009-03-05 23:03:49 +00001965 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001966 } else {
David Blaikie35506f82013-01-30 01:22:18 +00001967 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith938f40b2011-06-11 17:19:42 +00001968
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001969 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner97e277e2009-03-05 23:03:49 +00001970 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001971 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001972 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001973
1974 // Non-instance-fields can't have a bitfield.
1975 if (BitWidth) {
1976 if (Member->isInvalidDecl()) {
1977 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001978 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001979 // C++ 9.6p3: A bit-field shall not be a static member.
1980 // "static member 'A' cannot be a bit-field"
1981 Diag(Loc, diag::err_static_not_bitfield)
1982 << Name << BitWidth->getSourceRange();
1983 } else if (isa<TypedefDecl>(Member)) {
1984 // "typedef member 'x' cannot be a bit-field"
1985 Diag(Loc, diag::err_typedef_not_bitfield)
1986 << Name << BitWidth->getSourceRange();
1987 } else {
1988 // A function typedef ("typedef int f(); f a;").
1989 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1990 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001991 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001992 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001993 }
Mike Stump11289f42009-09-09 15:08:12 +00001994
Chris Lattnerd26760a2009-03-05 23:01:03 +00001995 BitWidth = 0;
1996 Member->setInvalidDecl();
1997 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001998
1999 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor3447e762009-08-20 22:52:58 +00002001 // If we have declared a member function template, set the access of the
2002 // templated declaration as well.
2003 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2004 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002005 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002006
Richard Smith18f07db2012-08-06 03:25:17 +00002007 if (VS.isOverrideSpecified())
2008 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2009 if (VS.isFinalSpecified())
2010 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonfd835532011-01-20 05:57:14 +00002011
Douglas Gregorf2f08062011-03-08 17:10:18 +00002012 if (VS.getLastLocation().isValid()) {
2013 // Update the end location of a method that has a virt-specifiers.
2014 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2015 MD->setRangeEnd(VS.getLastLocation());
2016 }
Richard Smith18f07db2012-08-06 03:25:17 +00002017
Anders Carlssonc87f8612011-01-20 06:29:02 +00002018 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002019
Douglas Gregor92751d42008-11-17 22:58:34 +00002020 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002021
Daniel Jasper0baec5492012-06-06 08:32:04 +00002022 if (isInstField) {
2023 FieldDecl *FD = cast<FieldDecl>(Member);
2024 FieldCollector->Add(FD);
2025
2026 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2027 FD->getLocation())
2028 != DiagnosticsEngine::Ignored) {
2029 // Remember all explicit private FieldDecls that have a name, no side
2030 // effects and are not part of a dependent type declaration.
2031 if (!FD->isImplicit() && FD->getDeclName() &&
2032 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002033 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002034 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002035 !InitializationHasSideEffects(*FD))
2036 UnusedPrivateFields.insert(FD);
2037 }
2038 }
2039
John McCall48871652010-08-21 09:40:31 +00002040 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002041}
2042
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002043namespace {
2044 class UninitializedFieldVisitor
2045 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2046 Sema &S;
2047 ValueDecl *VD;
2048 public:
2049 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2050 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002051 S(S) {
2052 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2053 this->VD = IFD->getAnonField();
2054 else
2055 this->VD = VD;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002056 }
2057
2058 void HandleExpr(Expr *E) {
2059 if (!E) return;
2060
2061 // Expressions like x(x) sometimes lack the surrounding expressions
2062 // but need to be checked anyways.
2063 HandleValue(E);
2064 Visit(E);
2065 }
2066
2067 void HandleValue(Expr *E) {
2068 E = E->IgnoreParens();
2069
2070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2071 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002072 return;
2073
2074 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2075 // or union.
2076 MemberExpr *FieldME = ME;
2077
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002078 Expr *Base = E;
2079 while (isa<MemberExpr>(Base)) {
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002080 ME = cast<MemberExpr>(Base);
2081
2082 if (isa<VarDecl>(ME->getMemberDecl()))
2083 return;
2084
2085 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2086 if (!FD->isAnonymousStructOrUnion())
2087 FieldME = ME;
2088
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002089 Base = ME->getBase();
2090 }
2091
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002092 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002093 unsigned diag = VD->getType()->isReferenceType()
2094 ? diag::warn_reference_field_is_uninit
2095 : diag::warn_field_is_uninit;
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002096 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002097 }
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002098 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002099 }
2100
2101 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2102 HandleValue(CO->getTrueExpr());
2103 HandleValue(CO->getFalseExpr());
2104 return;
2105 }
2106
2107 if (BinaryConditionalOperator *BCO =
2108 dyn_cast<BinaryConditionalOperator>(E)) {
2109 HandleValue(BCO->getCommon());
2110 HandleValue(BCO->getFalseExpr());
2111 return;
2112 }
2113
2114 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2115 switch (BO->getOpcode()) {
2116 default:
2117 return;
2118 case(BO_PtrMemD):
2119 case(BO_PtrMemI):
2120 HandleValue(BO->getLHS());
2121 return;
2122 case(BO_Comma):
2123 HandleValue(BO->getRHS());
2124 return;
2125 }
2126 }
2127 }
2128
2129 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2130 if (E->getCastKind() == CK_LValueToRValue)
2131 HandleValue(E->getSubExpr());
2132
2133 Inherited::VisitImplicitCastExpr(E);
2134 }
2135
2136 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2137 Expr *Callee = E->getCallee();
2138 if (isa<MemberExpr>(Callee))
2139 HandleValue(Callee);
2140
2141 Inherited::VisitCXXMemberCallExpr(E);
2142 }
2143 };
2144 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2145 ValueDecl *VD) {
2146 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2147 }
2148} // namespace
2149
Richard Smith938f40b2011-06-11 17:19:42 +00002150/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00002151/// in-class initializer for a non-static C++ class member, and after
2152/// instantiating an in-class initializer in a class template. Such actions
2153/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00002154void
Richard Smith2b013182012-06-10 03:12:00 +00002155Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith938f40b2011-06-11 17:19:42 +00002156 Expr *InitExpr) {
2157 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002158 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2159 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002160
2161 if (!InitExpr) {
2162 FD->setInvalidDecl();
2163 FD->removeInClassInitializer();
2164 return;
2165 }
2166
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002167 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2168 FD->setInvalidDecl();
2169 FD->removeInClassInitializer();
2170 return;
2171 }
2172
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002173 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2174 != DiagnosticsEngine::Ignored) {
2175 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2176 }
2177
Richard Smith938f40b2011-06-11 17:19:42 +00002178 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002179 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002180 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002181 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002182 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002183 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002184 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2185 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002186 if (Init.isInvalid()) {
2187 FD->setInvalidDecl();
2188 return;
2189 }
Richard Smith938f40b2011-06-11 17:19:42 +00002190 }
2191
Richard Smith945f8d32013-01-14 22:39:08 +00002192 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002193 // The initialization of each base and member constitutes a
2194 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002195 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002196 if (Init.isInvalid()) {
2197 FD->setInvalidDecl();
2198 return;
2199 }
2200
2201 InitExpr = Init.release();
2202
2203 FD->setInClassInitializer(InitExpr);
2204}
2205
Douglas Gregor15e77a22009-12-31 09:10:24 +00002206/// \brief Find the direct and/or virtual base specifiers that
2207/// correspond to the given base type, for use in base initialization
2208/// within a constructor.
2209static bool FindBaseInitializer(Sema &SemaRef,
2210 CXXRecordDecl *ClassDecl,
2211 QualType BaseType,
2212 const CXXBaseSpecifier *&DirectBaseSpec,
2213 const CXXBaseSpecifier *&VirtualBaseSpec) {
2214 // First, check for a direct base class.
2215 DirectBaseSpec = 0;
2216 for (CXXRecordDecl::base_class_const_iterator Base
2217 = ClassDecl->bases_begin();
2218 Base != ClassDecl->bases_end(); ++Base) {
2219 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2220 // We found a direct base of this type. That's what we're
2221 // initializing.
2222 DirectBaseSpec = &*Base;
2223 break;
2224 }
2225 }
2226
2227 // Check for a virtual base class.
2228 // FIXME: We might be able to short-circuit this if we know in advance that
2229 // there are no virtual bases.
2230 VirtualBaseSpec = 0;
2231 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2232 // We haven't found a base yet; search the class hierarchy for a
2233 // virtual base class.
2234 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2235 /*DetectVirtual=*/false);
2236 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2237 BaseType, Paths)) {
2238 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2239 Path != Paths.end(); ++Path) {
2240 if (Path->back().Base->isVirtual()) {
2241 VirtualBaseSpec = Path->back().Base;
2242 break;
2243 }
2244 }
2245 }
2246 }
2247
2248 return DirectBaseSpec || VirtualBaseSpec;
2249}
2250
Sebastian Redla74948d2011-09-24 17:48:25 +00002251/// \brief Handle a C++ member initializer using braced-init-list syntax.
2252MemInitResult
2253Sema::ActOnMemInitializer(Decl *ConstructorD,
2254 Scope *S,
2255 CXXScopeSpec &SS,
2256 IdentifierInfo *MemberOrBase,
2257 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002258 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002259 SourceLocation IdLoc,
2260 Expr *InitList,
2261 SourceLocation EllipsisLoc) {
2262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002263 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002264 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002265}
2266
2267/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002268MemInitResult
John McCall48871652010-08-21 09:40:31 +00002269Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002270 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002271 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002272 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002273 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002274 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002275 SourceLocation IdLoc,
2276 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002277 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002278 SourceLocation RParenLoc,
2279 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002280 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002281 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002282 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002283 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002284}
2285
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002286namespace {
2287
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002288// Callback to only accept typo corrections that can be a valid C++ member
2289// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002290class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2291 public:
2292 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2293 : ClassDecl(ClassDecl) {}
2294
2295 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2296 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2297 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2298 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2299 else
2300 return isa<TypeDecl>(ND);
2301 }
2302 return false;
2303 }
2304
2305 private:
2306 CXXRecordDecl *ClassDecl;
2307};
2308
2309}
2310
Sebastian Redla74948d2011-09-24 17:48:25 +00002311/// \brief Handle a C++ member initializer.
2312MemInitResult
2313Sema::BuildMemInitializer(Decl *ConstructorD,
2314 Scope *S,
2315 CXXScopeSpec &SS,
2316 IdentifierInfo *MemberOrBase,
2317 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002318 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002319 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002320 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002321 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002322 if (!ConstructorD)
2323 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002324
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002325 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002326
2327 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002328 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002329 if (!Constructor) {
2330 // The user wrote a constructor initializer on a function that is
2331 // not a C++ constructor. Ignore the error for now, because we may
2332 // have more member initializers coming; we'll diagnose it just
2333 // once in ActOnMemInitializers.
2334 return true;
2335 }
2336
2337 CXXRecordDecl *ClassDecl = Constructor->getParent();
2338
2339 // C++ [class.base.init]p2:
2340 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002341 // constructor's class and, if not found in that scope, are looked
2342 // up in the scope containing the constructor's definition.
2343 // [Note: if the constructor's class contains a member with the
2344 // same name as a direct or virtual base class of the class, a
2345 // mem-initializer-id naming the member or base class and composed
2346 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002347 // mem-initializer-id for the hidden base class may be specified
2348 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002349 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002350 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002351 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002352 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002353 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002354 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002355 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2356 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002357 if (EllipsisLoc.isValid())
2358 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002359 << MemberOrBase
2360 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002361
Sebastian Redla9351792012-02-11 23:51:47 +00002362 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002363 }
Francois Pichetd583da02010-12-04 09:14:42 +00002364 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002365 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002366 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002367 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002368 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002369
2370 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002371 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002372 } else if (DS.getTypeSpecType() == TST_decltype) {
2373 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002374 } else {
2375 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2376 LookupParsedName(R, S, &SS);
2377
2378 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2379 if (!TyD) {
2380 if (R.isAmbiguous()) return true;
2381
John McCallda6841b2010-04-09 19:01:14 +00002382 // We don't want access-control diagnostics here.
2383 R.suppressDiagnostics();
2384
Douglas Gregora3b624a2010-01-19 06:46:48 +00002385 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2386 bool NotUnknownSpecialization = false;
2387 DeclContext *DC = computeDeclContext(SS, false);
2388 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2389 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2390
2391 if (!NotUnknownSpecialization) {
2392 // When the scope specifier can refer to a member of an unknown
2393 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002394 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2395 SS.getWithLocInContext(Context),
2396 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002397 if (BaseType.isNull())
2398 return true;
2399
Douglas Gregora3b624a2010-01-19 06:46:48 +00002400 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002401 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002402 }
2403 }
2404
Douglas Gregor15e77a22009-12-31 09:10:24 +00002405 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002406 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002407 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002408 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002409 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002410 Validator, ClassDecl))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002411 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2412 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002413 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002414 // We have found a non-static data member with a similar
2415 // name to what was typed; complain and initialize that
2416 // member.
2417 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2418 << MemberOrBase << true << CorrectedQuotedStr
2419 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2420 Diag(Member->getLocation(), diag::note_previous_decl)
2421 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002422
Sebastian Redla9351792012-02-11 23:51:47 +00002423 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002424 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002425 const CXXBaseSpecifier *DirectBaseSpec;
2426 const CXXBaseSpecifier *VirtualBaseSpec;
2427 if (FindBaseInitializer(*this, ClassDecl,
2428 Context.getTypeDeclType(Type),
2429 DirectBaseSpec, VirtualBaseSpec)) {
2430 // We have found a direct or virtual base class with a
2431 // similar name to what was typed; complain and initialize
2432 // that base class.
2433 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002434 << MemberOrBase << false << CorrectedQuotedStr
2435 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00002436
2437 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2438 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002439 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002440 diag::note_base_class_specified_here)
2441 << BaseSpec->getType()
2442 << BaseSpec->getSourceRange();
2443
Douglas Gregor15e77a22009-12-31 09:10:24 +00002444 TyD = Type;
2445 }
2446 }
2447 }
2448
Douglas Gregora3b624a2010-01-19 06:46:48 +00002449 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002450 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002451 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002452 return true;
2453 }
John McCallb5a0d312009-12-21 10:41:20 +00002454 }
2455
Douglas Gregora3b624a2010-01-19 06:46:48 +00002456 if (BaseType.isNull()) {
2457 BaseType = Context.getTypeDeclType(TyD);
2458 if (SS.isSet()) {
2459 NestedNameSpecifier *Qualifier =
2460 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00002461
Douglas Gregora3b624a2010-01-19 06:46:48 +00002462 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00002463 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002464 }
John McCallb5a0d312009-12-21 10:41:20 +00002465 }
2466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
John McCallbcd03502009-12-07 02:54:59 +00002468 if (!TInfo)
2469 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002470
Sebastian Redla9351792012-02-11 23:51:47 +00002471 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002472}
2473
Chandler Carruth599deef2011-09-03 01:14:15 +00002474/// Checks a member initializer expression for cases where reference (or
2475/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002476static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2477 Expr *Init,
2478 SourceLocation IdLoc) {
2479 QualType MemberTy = Member->getType();
2480
2481 // We only handle pointers and references currently.
2482 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2483 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2484 return;
2485
2486 const bool IsPointer = MemberTy->isPointerType();
2487 if (IsPointer) {
2488 if (const UnaryOperator *Op
2489 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2490 // The only case we're worried about with pointers requires taking the
2491 // address.
2492 if (Op->getOpcode() != UO_AddrOf)
2493 return;
2494
2495 Init = Op->getSubExpr();
2496 } else {
2497 // We only handle address-of expression initializers for pointers.
2498 return;
2499 }
2500 }
2501
Richard Smithe3b28bc2013-06-12 21:51:50 +00002502 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002503 // We only warn when referring to a non-reference parameter declaration.
2504 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2505 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002506 return;
2507
2508 S.Diag(Init->getExprLoc(),
2509 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2510 : diag::warn_bind_ref_member_to_parameter)
2511 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002512 } else {
2513 // Other initializers are fine.
2514 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002515 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002516
2517 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2518 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002519}
2520
John McCallfaf5fb42010-08-26 23:41:50 +00002521MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002522Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002523 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002524 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2525 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2526 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002527 "Member must be a FieldDecl or IndirectFieldDecl");
2528
Sebastian Redla9351792012-02-11 23:51:47 +00002529 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002530 return true;
2531
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002532 if (Member->isInvalidDecl())
2533 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002534
John McCalle22a04a2009-11-04 23:02:40 +00002535 // Diagnose value-uses of fields to initialize themselves, e.g.
2536 // foo(foo)
2537 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002538 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002539 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002540 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002541 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002542 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002543 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002544 } else {
2545 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002546 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002547 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002548
Richard Trieu4fc85362012-06-14 23:11:34 +00002549 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2550 != DiagnosticsEngine::Ignored)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002551 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieu4fc85362012-06-14 23:11:34 +00002552 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002553 // initialized. For example, let this field be the i'th field. When
John McCalle22a04a2009-11-04 23:02:40 +00002554 // initializing the i'th field, throw a warning if any of the >= i'th
2555 // fields are used, as they are not yet initialized.
2556 // Right now we are only handling the case where the i'th field uses
2557 // itself in its initializer.
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002558 // Also need to take into account that some fields may be initialized by
2559 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieu4fc85362012-06-14 23:11:34 +00002560 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCalle22a04a2009-11-04 23:02:40 +00002561
Sebastian Redla9351792012-02-11 23:51:47 +00002562 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002563
Sebastian Redla9351792012-02-11 23:51:47 +00002564 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002565 // Can't check initialization for a member of dependent type or when
2566 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002567 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002568 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002569 bool InitList = false;
2570 if (isa<InitListExpr>(Init)) {
2571 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002572 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002573 }
2574
Chandler Carruthd44c3102010-12-06 09:23:57 +00002575 // Initialize the member.
2576 InitializedEntity MemberEntity =
2577 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2578 : InitializedEntity::InitializeMember(IndirectMember, 0);
2579 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002580 InitList ? InitializationKind::CreateDirectList(IdLoc)
2581 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2582 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002583
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002584 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2585 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002586 if (MemberInit.isInvalid())
2587 return true;
2588
Richard Smith736a9472013-06-12 20:42:33 +00002589 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2590
Richard Smith945f8d32013-01-14 22:39:08 +00002591 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002592 // The initialization of each base and member constitutes a
2593 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002594 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002595 if (MemberInit.isInvalid())
2596 return true;
2597
Richard Smithd59b8322012-12-19 01:39:02 +00002598 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002599 }
2600
Chandler Carruthd44c3102010-12-06 09:23:57 +00002601 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002602 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2603 InitRange.getBegin(), Init,
2604 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002605 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002606 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2607 InitRange.getBegin(), Init,
2608 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002609 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002610}
2611
John McCallfaf5fb42010-08-26 23:41:50 +00002612MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002613Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002614 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002615 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002616 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002617 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002618 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002619 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002620
Sebastian Redl0501c632012-02-12 16:37:36 +00002621 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002622 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002623 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2624 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002625 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002626 }
2627
Sebastian Redla9351792012-02-11 23:51:47 +00002628 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002629 // Initialize the object.
2630 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2631 QualType(ClassDecl->getTypeForDecl(), 0));
2632 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002633 InitList ? InitializationKind::CreateDirectList(NameLoc)
2634 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2635 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002636 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002637 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002638 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002639 if (DelegationInit.isInvalid())
2640 return true;
2641
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002642 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2643 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002644
Richard Smith945f8d32013-01-14 22:39:08 +00002645 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002646 // The initialization of each base and member constitutes a
2647 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002648 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2649 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002650 if (DelegationInit.isInvalid())
2651 return true;
2652
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002653 // If we are in a dependent context, template instantiation will
2654 // perform this type-checking again. Just save the arguments that we
2655 // received in a ParenListExpr.
2656 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2657 // of the information that we have about the base
2658 // initializer. However, deconstructing the ASTs is a dicey process,
2659 // and this approach is far more likely to get the corner cases right.
2660 if (CurContext->isDependentContext())
2661 DelegationInit = Owned(Init);
2662
Sebastian Redla9351792012-02-11 23:51:47 +00002663 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002664 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002665 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002666}
2667
2668MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002669Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002670 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002671 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002672 SourceLocation BaseLoc
2673 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002674
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002675 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2676 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2677 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2678
2679 // C++ [class.base.init]p2:
2680 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002681 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002682 // of that class, the mem-initializer is ill-formed. A
2683 // mem-initializer-list can initialize a base class using any
2684 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002685 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002686
Sebastian Redla9351792012-02-11 23:51:47 +00002687 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002688 if (EllipsisLoc.isValid()) {
2689 // This is a pack expansion.
2690 if (!BaseType->containsUnexpandedParameterPack()) {
2691 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002692 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002693
Douglas Gregor44e7df62011-01-04 00:32:56 +00002694 EllipsisLoc = SourceLocation();
2695 }
2696 } else {
2697 // Check for any unexpanded parameter packs.
2698 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2699 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002700
Sebastian Redla9351792012-02-11 23:51:47 +00002701 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002702 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002703 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002704
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002705 // Check for direct and virtual base classes.
2706 const CXXBaseSpecifier *DirectBaseSpec = 0;
2707 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2708 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002709 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2710 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002711 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002712
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002713 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2714 VirtualBaseSpec);
2715
2716 // C++ [base.class.init]p2:
2717 // Unless the mem-initializer-id names a nonstatic data member of the
2718 // constructor's class or a direct or virtual base of that class, the
2719 // mem-initializer is ill-formed.
2720 if (!DirectBaseSpec && !VirtualBaseSpec) {
2721 // If the class has any dependent bases, then it's possible that
2722 // one of those types will resolve to the same type as
2723 // BaseType. Therefore, just treat this as a dependent base
2724 // class initialization. FIXME: Should we try to check the
2725 // initialization anyway? It seems odd.
2726 if (ClassDecl->hasAnyDependentBases())
2727 Dependent = true;
2728 else
2729 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2730 << BaseType << Context.getTypeDeclType(ClassDecl)
2731 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2732 }
2733 }
2734
2735 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002736 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002737
Sebastian Redla74948d2011-09-24 17:48:25 +00002738 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2739 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002740 InitRange.getBegin(), Init,
2741 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002742 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002743
2744 // C++ [base.class.init]p2:
2745 // If a mem-initializer-id is ambiguous because it designates both
2746 // a direct non-virtual base class and an inherited virtual base
2747 // class, the mem-initializer is ill-formed.
2748 if (DirectBaseSpec && VirtualBaseSpec)
2749 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002750 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002751
Sebastian Redla9351792012-02-11 23:51:47 +00002752 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002753 if (!BaseSpec)
2754 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2755
2756 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002757 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002758 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002759 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002760 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002761 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002762 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002763
2764 InitializedEntity BaseEntity =
2765 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2766 InitializationKind Kind =
2767 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2768 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2769 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002770 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2771 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002772 if (BaseInit.isInvalid())
2773 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002774
Richard Smith945f8d32013-01-14 22:39:08 +00002775 // C++11 [class.base.init]p7:
2776 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002777 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002778 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002779 if (BaseInit.isInvalid())
2780 return true;
2781
2782 // If we are in a dependent context, template instantiation will
2783 // perform this type-checking again. Just save the arguments that we
2784 // received in a ParenListExpr.
2785 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2786 // of the information that we have about the base
2787 // initializer. However, deconstructing the ASTs is a dicey process,
2788 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002789 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002790 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002791
Alexis Hunt1d792652011-01-08 20:30:50 +00002792 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002793 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002794 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002795 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002796 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002797}
2798
Sebastian Redl22653ba2011-08-30 19:58:05 +00002799// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002800static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2801 if (T.isNull()) T = E->getType();
2802 QualType TargetType = SemaRef.BuildReferenceType(
2803 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002804 SourceLocation ExprLoc = E->getLocStart();
2805 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2806 TargetType, ExprLoc);
2807
2808 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2809 SourceRange(ExprLoc, ExprLoc),
2810 E->getSourceRange()).take();
2811}
2812
Anders Carlsson1b00e242010-04-23 03:10:23 +00002813/// ImplicitInitializerKind - How an implicit base or member initializer should
2814/// initialize its base or member.
2815enum ImplicitInitializerKind {
2816 IIK_Default,
2817 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002818 IIK_Move,
2819 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002820};
2821
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002822static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002823BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002824 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002825 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002826 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002827 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002828 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002829 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2830 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002831
John McCalldadc5752010-08-24 06:29:42 +00002832 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002833
2834 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00002835 case IIK_Inherit: {
2836 const CXXRecordDecl *Inherited =
2837 Constructor->getInheritedConstructor()->getParent();
2838 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2839 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2840 // C++11 [class.inhctor]p8:
2841 // Each expression in the expression-list is of the form
2842 // static_cast<T&&>(p), where p is the name of the corresponding
2843 // constructor parameter and T is the declared type of p.
2844 SmallVector<Expr*, 16> Args;
2845 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2846 ParmVarDecl *PD = Constructor->getParamDecl(I);
2847 ExprResult ArgExpr =
2848 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2849 VK_LValue, SourceLocation());
2850 if (ArgExpr.isInvalid())
2851 return true;
2852 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2853 }
2854
2855 InitializationKind InitKind = InitializationKind::CreateDirect(
2856 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002857 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00002858 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2859 break;
2860 }
2861 }
2862 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00002863 case IIK_Default: {
2864 InitializationKind InitKind
2865 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002866 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2867 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002868 break;
2869 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002870
Sebastian Redl22653ba2011-08-30 19:58:05 +00002871 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002872 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002873 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002874 ParmVarDecl *Param = Constructor->getParamDecl(0);
2875 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00002876
Anders Carlsson1b00e242010-04-23 03:10:23 +00002877 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002878 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00002879 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00002880 Constructor->getLocation(), ParamType,
2881 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002882
Eli Friedmanfa0df832012-02-02 03:46:19 +00002883 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2884
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002885 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002886 QualType ArgTy =
2887 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2888 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002889
Sebastian Redl22653ba2011-08-30 19:58:05 +00002890 if (Moving) {
2891 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2892 }
2893
John McCallcf142162010-08-07 06:22:56 +00002894 CXXCastPath BasePath;
2895 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002896 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2897 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002898 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002899 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002900
Anders Carlsson1b00e242010-04-23 03:10:23 +00002901 InitializationKind InitKind
2902 = InitializationKind::CreateDirect(Constructor->getLocation(),
2903 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002904 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2905 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002906 break;
2907 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002908 }
John McCallb268a282010-08-23 23:25:46 +00002909
Douglas Gregora40433a2010-12-07 00:41:46 +00002910 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002911 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002912 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002913
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002914 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002915 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002916 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2917 SourceLocation()),
2918 BaseSpec->isVirtual(),
2919 SourceLocation(),
2920 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002921 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002922 SourceLocation());
2923
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002924 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002925}
2926
Sebastian Redl22653ba2011-08-30 19:58:05 +00002927static bool RefersToRValueRef(Expr *MemRef) {
2928 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2929 return Referenced->getType()->isRValueReferenceType();
2930}
2931
Anders Carlsson3c1db572010-04-23 02:15:47 +00002932static bool
2933BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002934 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002935 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002936 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002937 if (Field->isInvalidDecl())
2938 return true;
2939
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002940 SourceLocation Loc = Constructor->getLocation();
2941
Sebastian Redl22653ba2011-08-30 19:58:05 +00002942 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2943 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002944 ParmVarDecl *Param = Constructor->getParamDecl(0);
2945 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002946
2947 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00002948 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2949 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002950
Anders Carlsson423f5d82010-04-23 16:04:08 +00002951 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002952 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00002953 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00002954 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002955
Eli Friedmanfa0df832012-02-02 03:46:19 +00002956 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2957
Sebastian Redl22653ba2011-08-30 19:58:05 +00002958 if (Moving) {
2959 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2960 }
2961
Douglas Gregor94f9a482010-05-05 05:51:00 +00002962 // Build a reference to this field within the parameter.
2963 CXXScopeSpec SS;
2964 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2965 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002966 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2967 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002968 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002969 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002970 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002971 ParamType, Loc,
2972 /*IsArrow=*/false,
2973 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002974 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002975 /*FirstQualifierInScope=*/0,
2976 MemberLookup,
2977 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002978 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002979 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002980
2981 // C++11 [class.copy]p15:
2982 // - if a member m has rvalue reference type T&&, it is direct-initialized
2983 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002984 if (RefersToRValueRef(CtorArg.get())) {
2985 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002986 }
2987
Douglas Gregor94f9a482010-05-05 05:51:00 +00002988 // When the field we are copying is an array, create index variables for
2989 // each dimension of the array. We use these index variables to subscript
2990 // the source array, and other clients (e.g., CodeGen) will perform the
2991 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002992 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002993 QualType BaseType = Field->getType();
2994 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002995 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002996 while (const ConstantArrayType *Array
2997 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002998 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002999 // Create the iteration variable for this array index.
3000 IdentifierInfo *IterationVarName = 0;
3001 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003002 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003003 llvm::raw_svector_ostream OS(Str);
3004 OS << "__i" << IndexVariables.size();
3005 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3006 }
3007 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003008 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003009 IterationVarName, SizeType,
3010 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003011 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003012 IndexVariables.push_back(IterationVar);
3013
3014 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003015 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003016 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003017 assert(!IterationVarRef.isInvalid() &&
3018 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003019 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3020 assert(!IterationVarRef.isInvalid() &&
3021 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003022
Douglas Gregor94f9a482010-05-05 05:51:00 +00003023 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003024 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003025 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003026 Loc);
3027 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003028 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003029
Douglas Gregor94f9a482010-05-05 05:51:00 +00003030 BaseType = Array->getElementType();
3031 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003032
3033 // The array subscript expression is an lvalue, which is wrong for moving.
3034 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003035 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003036
Douglas Gregor94f9a482010-05-05 05:51:00 +00003037 // Construct the entity that we will be initializing. For an array, this
3038 // will be first element in the array, which may require several levels
3039 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003040 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003041 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003042 if (Indirect)
3043 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3044 else
3045 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003046 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3047 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3048 0,
3049 Entities.back()));
3050
3051 // Direct-initialize to use the copy constructor.
3052 InitializationKind InitKind =
3053 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3054
Sebastian Redle9c4e842011-09-04 18:14:28 +00003055 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003056 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003057
John McCalldadc5752010-08-24 06:29:42 +00003058 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003059 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003060 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003061 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003062 if (MemberInit.isInvalid())
3063 return true;
3064
Douglas Gregor493627b2011-08-10 15:22:55 +00003065 if (Indirect) {
3066 assert(IndexVariables.size() == 0 &&
3067 "Indirect field improperly initialized");
3068 CXXMemberInit
3069 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3070 Loc, Loc,
3071 MemberInit.takeAs<Expr>(),
3072 Loc);
3073 } else
3074 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3075 Loc, MemberInit.takeAs<Expr>(),
3076 Loc,
3077 IndexVariables.data(),
3078 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003079 return false;
3080 }
3081
Richard Smithc2bc61b2013-03-18 21:12:30 +00003082 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3083 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003084
Anders Carlsson3c1db572010-04-23 02:15:47 +00003085 QualType FieldBaseElementType =
3086 SemaRef.Context.getBaseElementType(Field->getType());
3087
Anders Carlsson3c1db572010-04-23 02:15:47 +00003088 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003089 InitializedEntity InitEntity
3090 = Indirect? InitializedEntity::InitializeMember(Indirect)
3091 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003092 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003093 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003094
3095 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3096 ExprResult MemberInit =
3097 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003098
Douglas Gregora40433a2010-12-07 00:41:46 +00003099 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003100 if (MemberInit.isInvalid())
3101 return true;
3102
Douglas Gregor493627b2011-08-10 15:22:55 +00003103 if (Indirect)
3104 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3105 Indirect, Loc,
3106 Loc,
3107 MemberInit.get(),
3108 Loc);
3109 else
3110 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3111 Field, Loc, Loc,
3112 MemberInit.get(),
3113 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003114 return false;
3115 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003116
Alexis Hunt8b455182011-05-17 00:19:05 +00003117 if (!Field->getParent()->isUnion()) {
3118 if (FieldBaseElementType->isReferenceType()) {
3119 SemaRef.Diag(Constructor->getLocation(),
3120 diag::err_uninitialized_member_in_ctor)
3121 << (int)Constructor->isImplicit()
3122 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3123 << 0 << Field->getDeclName();
3124 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3125 return true;
3126 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003127
Alexis Hunt8b455182011-05-17 00:19:05 +00003128 if (FieldBaseElementType.isConstQualified()) {
3129 SemaRef.Diag(Constructor->getLocation(),
3130 diag::err_uninitialized_member_in_ctor)
3131 << (int)Constructor->isImplicit()
3132 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3133 << 1 << Field->getDeclName();
3134 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3135 return true;
3136 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003137 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003138
David Blaikiebbafb8a2012-03-11 07:00:24 +00003139 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003140 FieldBaseElementType->isObjCRetainableType() &&
3141 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3142 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003143 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003144 // Default-initialize Objective-C pointers to NULL.
3145 CXXMemberInit
3146 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3147 Loc, Loc,
3148 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3149 Loc);
3150 return false;
3151 }
3152
Anders Carlsson3c1db572010-04-23 02:15:47 +00003153 // Nothing to initialize.
3154 CXXMemberInit = 0;
3155 return false;
3156}
John McCallbc83b3f2010-05-20 23:23:51 +00003157
3158namespace {
3159struct BaseAndFieldInfo {
3160 Sema &S;
3161 CXXConstructorDecl *Ctor;
3162 bool AnyErrorsInInits;
3163 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003164 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003165 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003166
3167 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3168 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003169 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3170 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003171 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003172 else if (Generated && Ctor->isMoveConstructor())
3173 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003174 else if (Ctor->getInheritedConstructor())
3175 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003176 else
3177 IIK = IIK_Default;
3178 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003179
3180 bool isImplicitCopyOrMove() const {
3181 switch (IIK) {
3182 case IIK_Copy:
3183 case IIK_Move:
3184 return true;
3185
3186 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003187 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003188 return false;
3189 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003190
3191 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003192 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003193
3194 bool addFieldInitializer(CXXCtorInitializer *Init) {
3195 AllToInit.push_back(Init);
3196
3197 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003198 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003199 S.UnusedPrivateFields.remove(Init->getAnyMember());
3200
3201 return false;
3202 }
John McCallbc83b3f2010-05-20 23:23:51 +00003203};
3204}
3205
Richard Smithc94ec842011-09-19 13:34:43 +00003206/// \brief Determine whether the given indirect field declaration is somewhere
3207/// within an anonymous union.
3208static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3209 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3210 CEnd = F->chain_end();
3211 C != CEnd; ++C)
3212 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3213 if (Record->isUnion())
3214 return true;
3215
3216 return false;
3217}
3218
Douglas Gregor10f939c2011-11-02 23:04:16 +00003219/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3220/// array type.
3221static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3222 if (T->isIncompleteArrayType())
3223 return true;
3224
3225 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3226 if (!ArrayT->getSize())
3227 return true;
3228
3229 T = ArrayT->getElementType();
3230 }
3231
3232 return false;
3233}
3234
Richard Smith938f40b2011-06-11 17:19:42 +00003235static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003236 FieldDecl *Field,
3237 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00003238
Chandler Carruth139e9622010-06-30 02:59:29 +00003239 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003240 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3241 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003242
Richard Smith0a8cfc72012-08-07 21:30:42 +00003243 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith938f40b2011-06-11 17:19:42 +00003244 // has a brace-or-equal-initializer, the entity is initialized as specified
3245 // in [dcl.init].
Douglas Gregor7db3e952011-11-28 20:03:15 +00003246 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003247 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3248 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003249 CXXCtorInitializer *Init;
3250 if (Indirect)
3251 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3252 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003253 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003254 SourceLocation());
3255 else
3256 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3257 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003258 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003259 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003260 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003261 }
3262
Richard Smith12d5ed82011-09-18 11:14:50 +00003263 // Don't build an implicit initializer for union members if none was
3264 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00003265 if (Field->getParent()->isUnion() ||
3266 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00003267 return false;
3268
Douglas Gregor10f939c2011-11-02 23:04:16 +00003269 // Don't initialize incomplete or zero-length arrays.
3270 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3271 return false;
3272
John McCallbc83b3f2010-05-20 23:23:51 +00003273 // Don't try to build an implicit initializer if there were semantic
3274 // errors in any of the initializers (and therefore we might be
3275 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00003276 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00003277 return false;
3278
Alexis Hunt1d792652011-01-08 20:30:50 +00003279 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003280 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3281 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003282 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003283
Richard Smith0a8cfc72012-08-07 21:30:42 +00003284 if (!Init)
3285 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003286
Richard Smith0a8cfc72012-08-07 21:30:42 +00003287 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003288}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003289
3290bool
3291Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3292 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003293 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003294 Constructor->setNumCtorInitializers(1);
3295 CXXCtorInitializer **initializer =
3296 new (Context) CXXCtorInitializer*[1];
3297 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3298 Constructor->setCtorInitializers(initializer);
3299
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003300 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003301 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003302 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3303 }
3304
Alexis Hunte2622992011-05-05 00:05:47 +00003305 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003306
Alexis Hunt61bc1732011-05-01 07:04:31 +00003307 return false;
3308}
Douglas Gregor493627b2011-08-10 15:22:55 +00003309
David Blaikie3fc2f912013-01-17 05:26:25 +00003310bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3311 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003312 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003313 // Just store the initializers as written, they will be checked during
3314 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003315 if (!Initializers.empty()) {
3316 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003317 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003318 new (Context) CXXCtorInitializer*[Initializers.size()];
3319 memcpy(baseOrMemberInitializers, Initializers.data(),
3320 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003321 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003322 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003323
3324 // Let template instantiation know whether we had errors.
3325 if (AnyErrors)
3326 Constructor->setInvalidDecl();
3327
Anders Carlssondb0a9652010-04-02 06:26:44 +00003328 return false;
3329 }
3330
John McCallbc83b3f2010-05-20 23:23:51 +00003331 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003332
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003333 // We need to build the initializer AST according to order of construction
3334 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003335 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003336 if (!ClassDecl)
3337 return true;
3338
Eli Friedman9cf6b592009-11-09 19:20:36 +00003339 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003340
David Blaikie3fc2f912013-01-17 05:26:25 +00003341 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003342 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00003343
3344 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003345 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003346 else
Francois Pichetd583da02010-12-04 09:14:42 +00003347 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003348 }
3349
Anders Carlsson43c64af2010-04-21 19:52:01 +00003350 // Keep track of the direct virtual bases.
3351 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3352 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3353 E = ClassDecl->bases_end(); I != E; ++I) {
3354 if (I->isVirtual())
3355 DirectVBases.insert(I);
3356 }
3357
Anders Carlssondb0a9652010-04-02 06:26:44 +00003358 // Push virtual bases before others.
3359 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3360 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3361
Alexis Hunt1d792652011-01-08 20:30:50 +00003362 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003363 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3364 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003365 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00003366 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003367 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003368 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003369 VBase, IsInheritedVirtualBase,
3370 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003371 HadError = true;
3372 continue;
3373 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003374
John McCallbc83b3f2010-05-20 23:23:51 +00003375 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003376 }
3377 }
Mike Stump11289f42009-09-09 15:08:12 +00003378
John McCallbc83b3f2010-05-20 23:23:51 +00003379 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00003380 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3381 E = ClassDecl->bases_end(); Base != E; ++Base) {
3382 // Virtuals are in the virtual base list and already constructed.
3383 if (Base->isVirtual())
3384 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003385
Alexis Hunt1d792652011-01-08 20:30:50 +00003386 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003387 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3388 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003389 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003390 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003391 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003392 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003393 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003394 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003395 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003396 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003397
John McCallbc83b3f2010-05-20 23:23:51 +00003398 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003399 }
3400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
John McCallbc83b3f2010-05-20 23:23:51 +00003402 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00003403 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3404 MemEnd = ClassDecl->decls_end();
3405 Mem != MemEnd; ++Mem) {
3406 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003407 // C++ [class.bit]p2:
3408 // A declaration for a bit-field that omits the identifier declares an
3409 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3410 // initialized.
3411 if (F->isUnnamedBitfield())
3412 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003413
Sebastian Redl22653ba2011-08-30 19:58:05 +00003414 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003415 // handle anonymous struct/union fields based on their individual
3416 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003417 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003418 continue;
3419
3420 if (CollectFieldInitializer(*this, Info, F))
3421 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003422 continue;
3423 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003424
3425 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003426 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003427 continue;
3428
3429 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3430 if (F->getType()->isIncompleteArrayType()) {
3431 assert(ClassDecl->hasFlexibleArrayMember() &&
3432 "Incomplete array type is not valid");
3433 continue;
3434 }
3435
Douglas Gregor493627b2011-08-10 15:22:55 +00003436 // Initialize each field of an anonymous struct individually.
3437 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3438 HadError = true;
3439
3440 continue;
3441 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003442 }
Mike Stump11289f42009-09-09 15:08:12 +00003443
David Blaikie3fc2f912013-01-17 05:26:25 +00003444 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003445 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003446 Constructor->setNumCtorInitializers(NumInitializers);
3447 CXXCtorInitializer **baseOrMemberInitializers =
3448 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003449 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003450 NumInitializers * sizeof(CXXCtorInitializer*));
3451 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003452
John McCalla6309952010-03-16 21:39:52 +00003453 // Constructors implicitly reference the base and member
3454 // destructors.
3455 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3456 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003457 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003458
3459 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003460}
3461
David Blaikieb61b8152013-01-17 08:49:22 +00003462static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003463 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003464 const RecordDecl *RD = RT->getDecl();
3465 if (RD->isAnonymousStructOrUnion()) {
3466 for (RecordDecl::field_iterator Field = RD->field_begin(),
3467 E = RD->field_end(); Field != E; ++Field)
3468 PopulateKeysForFields(*Field, IdealInits);
3469 return;
3470 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003471 }
David Blaikieb61b8152013-01-17 08:49:22 +00003472 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003473}
3474
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003475static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00003476 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003477}
3478
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003479static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00003480 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003481 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003482 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003483
David Blaikieb61b8152013-01-17 08:49:22 +00003484 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003485}
3486
David Blaikie3fc2f912013-01-17 05:26:25 +00003487static void DiagnoseBaseOrMemInitializerOrder(
3488 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3489 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003490 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003491 return;
Mike Stump11289f42009-09-09 15:08:12 +00003492
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003493 // Don't check initializers order unless the warning is enabled at the
3494 // location of at least one initializer.
3495 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003496 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003497 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003498 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3499 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003500 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003501 ShouldCheckOrder = true;
3502 break;
3503 }
3504 }
3505 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003506 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003507
John McCallbb7b6582010-04-10 07:37:23 +00003508 // Build the list of bases and members in the order that they'll
3509 // actually be initialized. The explicit initializers should be in
3510 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003511 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003512
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003513 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3514
John McCallbb7b6582010-04-10 07:37:23 +00003515 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003516 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003517 ClassDecl->vbases_begin(),
3518 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003519 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003520
John McCallbb7b6582010-04-10 07:37:23 +00003521 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003522 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003523 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003524 if (Base->isVirtual())
3525 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003526 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003527 }
Mike Stump11289f42009-09-09 15:08:12 +00003528
John McCallbb7b6582010-04-10 07:37:23 +00003529 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003530 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003531 E = ClassDecl->field_end(); Field != E; ++Field) {
3532 if (Field->isUnnamedBitfield())
3533 continue;
3534
David Blaikieb61b8152013-01-17 08:49:22 +00003535 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003536 }
3537
John McCallbb7b6582010-04-10 07:37:23 +00003538 unsigned NumIdealInits = IdealInitKeys.size();
3539 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003540
Alexis Hunt1d792652011-01-08 20:30:50 +00003541 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003542 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003543 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00003544 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003545
3546 // Scan forward to try to find this initializer in the idealized
3547 // initializers list.
3548 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3549 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003550 break;
John McCallbb7b6582010-04-10 07:37:23 +00003551
3552 // If we didn't find this initializer, it must be because we
3553 // scanned past it on a previous iteration. That can only
3554 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003555 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003556 Sema::SemaDiagnosticBuilder D =
3557 SemaRef.Diag(PrevInit->getSourceLocation(),
3558 diag::warn_initializer_out_of_order);
3559
Francois Pichetd583da02010-12-04 09:14:42 +00003560 if (PrevInit->isAnyMemberInitializer())
3561 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003562 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003563 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003564
Francois Pichetd583da02010-12-04 09:14:42 +00003565 if (Init->isAnyMemberInitializer())
3566 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003567 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003568 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003569
3570 // Move back to the initializer's location in the ideal list.
3571 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3572 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003573 break;
John McCallbb7b6582010-04-10 07:37:23 +00003574
3575 assert(IdealIndex != NumIdealInits &&
3576 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003577 }
John McCallbb7b6582010-04-10 07:37:23 +00003578
3579 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003580 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003581}
3582
John McCall23eebd92010-04-10 09:28:51 +00003583namespace {
3584bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003585 CXXCtorInitializer *Init,
3586 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003587 if (!PrevInit) {
3588 PrevInit = Init;
3589 return false;
3590 }
3591
Douglas Gregorea306a12013-03-25 23:28:23 +00003592 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003593 S.Diag(Init->getSourceLocation(),
3594 diag::err_multiple_mem_initialization)
3595 << Field->getDeclName()
3596 << Init->getSourceRange();
3597 else {
John McCall424cec92011-01-19 06:33:43 +00003598 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003599 assert(BaseClass && "neither field nor base");
3600 S.Diag(Init->getSourceLocation(),
3601 diag::err_multiple_base_initialization)
3602 << QualType(BaseClass, 0)
3603 << Init->getSourceRange();
3604 }
3605 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3606 << 0 << PrevInit->getSourceRange();
3607
3608 return true;
3609}
3610
Alexis Hunt1d792652011-01-08 20:30:50 +00003611typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003612typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3613
3614bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003615 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003616 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003617 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003618 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003619 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003620
3621 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003622 if (Parent->isUnion()) {
3623 UnionEntry &En = Unions[Parent];
3624 if (En.first && En.first != Child) {
3625 S.Diag(Init->getSourceLocation(),
3626 diag::err_multiple_mem_union_initialization)
3627 << Field->getDeclName()
3628 << Init->getSourceRange();
3629 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3630 << 0 << En.second->getSourceRange();
3631 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003632 }
3633 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003634 En.first = Child;
3635 En.second = Init;
3636 }
David Blaikie0f65d592011-11-17 06:01:57 +00003637 if (!Parent->isAnonymousStructOrUnion())
3638 return false;
John McCall23eebd92010-04-10 09:28:51 +00003639 }
3640
3641 Child = Parent;
3642 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003643 }
John McCall23eebd92010-04-10 09:28:51 +00003644
3645 return false;
3646}
3647}
3648
Anders Carlssone857b292010-04-02 03:37:03 +00003649/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003650void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003651 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003652 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003653 bool AnyErrors) {
3654 if (!ConstructorDecl)
3655 return;
3656
3657 AdjustDeclIfTemplate(ConstructorDecl);
3658
3659 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003660 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003661
3662 if (!Constructor) {
3663 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3664 return;
3665 }
3666
John McCall23eebd92010-04-10 09:28:51 +00003667 // Mapping for the duplicate initializers check.
3668 // For member initializers, this is keyed with a FieldDecl*.
3669 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003670 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003671
3672 // Mapping for the inconsistent anonymous-union initializers check.
3673 RedundantUnionMap MemberUnions;
3674
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003675 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003676 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003677 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003678
Abramo Bagnara341d7832010-05-26 18:09:23 +00003679 // Set the source order index.
3680 Init->setSourceOrder(i);
3681
Francois Pichetd583da02010-12-04 09:14:42 +00003682 if (Init->isAnyMemberInitializer()) {
3683 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003684 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3685 CheckRedundantUnionInit(*this, Init, MemberUnions))
3686 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003687 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003688 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3689 if (CheckRedundantInit(*this, Init, Members[Key]))
3690 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003691 } else {
3692 assert(Init->isDelegatingInitializer());
3693 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003694 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003695 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003696 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003697 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003698 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003699 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003700 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003701 // Return immediately as the initializer is set.
3702 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003703 }
Anders Carlssone857b292010-04-02 03:37:03 +00003704 }
3705
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003706 if (HadError)
3707 return;
3708
David Blaikie3fc2f912013-01-17 05:26:25 +00003709 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003710
David Blaikie3fc2f912013-01-17 05:26:25 +00003711 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlssone857b292010-04-02 03:37:03 +00003712}
3713
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003714void
John McCalla6309952010-03-16 21:39:52 +00003715Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3716 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003717 // Ignore dependent contexts. Also ignore unions, since their members never
3718 // have destructors implicitly called.
3719 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003720 return;
John McCall1064d7e2010-03-16 05:22:47 +00003721
3722 // FIXME: all the access-control diagnostics are positioned on the
3723 // field/base declaration. That's probably good; that said, the
3724 // user might reasonably want to know why the destructor is being
3725 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003726
Anders Carlssondee9a302009-11-17 04:44:12 +00003727 // Non-static data members.
3728 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3729 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00003730 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003731 if (Field->isInvalidDecl())
3732 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003733
3734 // Don't destroy incomplete or zero-length arrays.
3735 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3736 continue;
3737
Anders Carlssondee9a302009-11-17 04:44:12 +00003738 QualType FieldType = Context.getBaseElementType(Field->getType());
3739
3740 const RecordType* RT = FieldType->getAs<RecordType>();
3741 if (!RT)
3742 continue;
3743
3744 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003745 if (FieldClassDecl->isInvalidDecl())
3746 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003747 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003748 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003749 // The destructor for an implicit anonymous union member is never invoked.
3750 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3751 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003752
Douglas Gregore71edda2010-07-01 22:47:18 +00003753 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003754 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003755 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003756 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003757 << Field->getDeclName()
3758 << FieldType);
3759
Eli Friedmanfa0df832012-02-02 03:46:19 +00003760 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smitheec915d62012-02-18 04:13:32 +00003761 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003762 }
3763
John McCall1064d7e2010-03-16 05:22:47 +00003764 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3765
Anders Carlssondee9a302009-11-17 04:44:12 +00003766 // Bases.
3767 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3768 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003769 // Bases are always records in a well-formed non-dependent class.
3770 const RecordType *RT = Base->getType()->getAs<RecordType>();
3771
3772 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003773 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003774 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003775
John McCall1064d7e2010-03-16 05:22:47 +00003776 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003777 // If our base class is invalid, we probably can't get its dtor anyway.
3778 if (BaseClassDecl->isInvalidDecl())
3779 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003780 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003781 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003782
Douglas Gregore71edda2010-07-01 22:47:18 +00003783 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003784 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003785
3786 // FIXME: caret should be on the start of the class name
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003787 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003788 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003789 << Base->getType()
John McCall5dadb652012-04-07 03:04:20 +00003790 << Base->getSourceRange(),
3791 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00003792
Eli Friedmanfa0df832012-02-02 03:46:19 +00003793 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smitheec915d62012-02-18 04:13:32 +00003794 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003795 }
3796
3797 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003798 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3799 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003800
3801 // Bases are always records in a well-formed non-dependent class.
John McCalldd1eca32012-04-09 21:51:56 +00003802 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003803
3804 // Ignore direct virtual bases.
3805 if (DirectVirtualBases.count(RT))
3806 continue;
3807
John McCall1064d7e2010-03-16 05:22:47 +00003808 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003809 // If our base class is invalid, we probably can't get its dtor anyway.
3810 if (BaseClassDecl->isInvalidDecl())
3811 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003812 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003813 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003814
Douglas Gregore71edda2010-07-01 22:47:18 +00003815 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003816 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00003817 if (CheckDestructorAccess(
3818 ClassDecl->getLocation(), Dtor,
3819 PDiag(diag::err_access_dtor_vbase)
3820 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3821 Context.getTypeDeclType(ClassDecl)) ==
3822 AR_accessible) {
3823 CheckDerivedToBaseConversion(
3824 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3825 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3826 SourceRange(), DeclarationName(), 0);
3827 }
John McCall1064d7e2010-03-16 05:22:47 +00003828
Eli Friedmanfa0df832012-02-02 03:46:19 +00003829 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smitheec915d62012-02-18 04:13:32 +00003830 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003831 }
3832}
3833
John McCall48871652010-08-21 09:40:31 +00003834void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003835 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003836 return;
Mike Stump11289f42009-09-09 15:08:12 +00003837
Mike Stump11289f42009-09-09 15:08:12 +00003838 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003839 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie3fc2f912013-01-17 05:26:25 +00003840 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003841}
3842
Mike Stump11289f42009-09-09 15:08:12 +00003843bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003844 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00003845 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3846 unsigned DiagID;
3847 AbstractDiagSelID SelID;
3848
3849 public:
3850 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3851 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3852
3853 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00003854 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00003855 if (SelID == -1)
3856 S.Diag(Loc, DiagID) << T;
3857 else
3858 S.Diag(Loc, DiagID) << SelID << T;
3859 }
3860 } Diagnoser(DiagID, SelID);
3861
3862 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00003863}
3864
Anders Carlssoneabf7702009-08-27 00:13:57 +00003865bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00003866 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003867 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003868 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003869
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003870 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00003871 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00003872
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003873 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003874 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003875 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003876 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003877
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003878 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00003879 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003880 }
Mike Stump11289f42009-09-09 15:08:12 +00003881
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003882 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003883 if (!RT)
3884 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003885
John McCall67da35c2010-02-04 22:26:26 +00003886 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003887
John McCall02db245d2010-08-18 09:41:07 +00003888 // We can't answer whether something is abstract until it has a
3889 // definition. If it's currently being defined, we'll walk back
3890 // over all the declarations when we have a full definition.
3891 const CXXRecordDecl *Def = RD->getDefinition();
3892 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003893 return false;
3894
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003895 if (!RD->isAbstract())
3896 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003897
Douglas Gregorae298422012-05-04 17:09:59 +00003898 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00003899 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003900
John McCall02db245d2010-08-18 09:41:07 +00003901 return true;
3902}
3903
3904void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3905 // Check if we've already emitted the list of pure virtual functions
3906 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003907 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003908 return;
Mike Stump11289f42009-09-09 15:08:12 +00003909
Douglas Gregor4165bd62010-03-23 23:47:56 +00003910 CXXFinalOverriderMap FinalOverriders;
3911 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003912
Anders Carlssona2f74f32010-06-03 01:00:02 +00003913 // Keep a set of seen pure methods so we won't diagnose the same method
3914 // more than once.
3915 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3916
Douglas Gregor4165bd62010-03-23 23:47:56 +00003917 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3918 MEnd = FinalOverriders.end();
3919 M != MEnd;
3920 ++M) {
3921 for (OverridingMethods::iterator SO = M->second.begin(),
3922 SOEnd = M->second.end();
3923 SO != SOEnd; ++SO) {
3924 // C++ [class.abstract]p4:
3925 // A class is abstract if it contains or inherits at least one
3926 // pure virtual function for which the final overrider is pure
3927 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003928
Douglas Gregor4165bd62010-03-23 23:47:56 +00003929 //
3930 if (SO->second.size() != 1)
3931 continue;
3932
3933 if (!SO->second.front().Method->isPure())
3934 continue;
3935
Anders Carlssona2f74f32010-06-03 01:00:02 +00003936 if (!SeenPureMethods.insert(SO->second.front().Method))
3937 continue;
3938
Douglas Gregor4165bd62010-03-23 23:47:56 +00003939 Diag(SO->second.front().Method->getLocation(),
3940 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003941 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003942 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003943 }
3944
3945 if (!PureVirtualClassDiagSet)
3946 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3947 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003948}
3949
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003950namespace {
John McCall02db245d2010-08-18 09:41:07 +00003951struct AbstractUsageInfo {
3952 Sema &S;
3953 CXXRecordDecl *Record;
3954 CanQualType AbstractType;
3955 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003956
John McCall02db245d2010-08-18 09:41:07 +00003957 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3958 : S(S), Record(Record),
3959 AbstractType(S.Context.getCanonicalType(
3960 S.Context.getTypeDeclType(Record))),
3961 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003962
John McCall02db245d2010-08-18 09:41:07 +00003963 void DiagnoseAbstractType() {
3964 if (Invalid) return;
3965 S.DiagnoseAbstractType(Record);
3966 Invalid = true;
3967 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003968
John McCall02db245d2010-08-18 09:41:07 +00003969 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3970};
3971
3972struct CheckAbstractUsage {
3973 AbstractUsageInfo &Info;
3974 const NamedDecl *Ctx;
3975
3976 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3977 : Info(Info), Ctx(Ctx) {}
3978
3979 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3980 switch (TL.getTypeLocClass()) {
3981#define ABSTRACT_TYPELOC(CLASS, PARENT)
3982#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00003983 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00003984#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003985 }
John McCall02db245d2010-08-18 09:41:07 +00003986 }
Mike Stump11289f42009-09-09 15:08:12 +00003987
John McCall02db245d2010-08-18 09:41:07 +00003988 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3989 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3990 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003991 if (!TL.getArg(I))
3992 continue;
3993
John McCall02db245d2010-08-18 09:41:07 +00003994 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3995 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003996 }
John McCall02db245d2010-08-18 09:41:07 +00003997 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003998
John McCall02db245d2010-08-18 09:41:07 +00003999 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4000 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4001 }
Mike Stump11289f42009-09-09 15:08:12 +00004002
John McCall02db245d2010-08-18 09:41:07 +00004003 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4004 // Visit the type parameters from a permissive context.
4005 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4006 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4007 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4008 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4009 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4010 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004011 }
John McCall02db245d2010-08-18 09:41:07 +00004012 }
Mike Stump11289f42009-09-09 15:08:12 +00004013
John McCall02db245d2010-08-18 09:41:07 +00004014 // Visit pointee types from a permissive context.
4015#define CheckPolymorphic(Type) \
4016 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4017 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4018 }
4019 CheckPolymorphic(PointerTypeLoc)
4020 CheckPolymorphic(ReferenceTypeLoc)
4021 CheckPolymorphic(MemberPointerTypeLoc)
4022 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004023 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004024
John McCall02db245d2010-08-18 09:41:07 +00004025 /// Handle all the types we haven't given a more specific
4026 /// implementation for above.
4027 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4028 // Every other kind of type that we haven't called out already
4029 // that has an inner type is either (1) sugar or (2) contains that
4030 // inner type in some way as a subobject.
4031 if (TypeLoc Next = TL.getNextTypeLoc())
4032 return Visit(Next, Sel);
4033
4034 // If there's no inner type and we're in a permissive context,
4035 // don't diagnose.
4036 if (Sel == Sema::AbstractNone) return;
4037
4038 // Check whether the type matches the abstract type.
4039 QualType T = TL.getType();
4040 if (T->isArrayType()) {
4041 Sel = Sema::AbstractArrayType;
4042 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004043 }
John McCall02db245d2010-08-18 09:41:07 +00004044 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4045 if (CT != Info.AbstractType) return;
4046
4047 // It matched; do some magic.
4048 if (Sel == Sema::AbstractArrayType) {
4049 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4050 << T << TL.getSourceRange();
4051 } else {
4052 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4053 << Sel << T << TL.getSourceRange();
4054 }
4055 Info.DiagnoseAbstractType();
4056 }
4057};
4058
4059void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4060 Sema::AbstractDiagSelID Sel) {
4061 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4062}
4063
4064}
4065
4066/// Check for invalid uses of an abstract type in a method declaration.
4067static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4068 CXXMethodDecl *MD) {
4069 // No need to do the check on definitions, which require that
4070 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004071 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004072 return;
4073
4074 // For safety's sake, just ignore it if we don't have type source
4075 // information. This should never happen for non-implicit methods,
4076 // but...
4077 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4078 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4079}
4080
4081/// Check for invalid uses of an abstract type within a class definition.
4082static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4083 CXXRecordDecl *RD) {
4084 for (CXXRecordDecl::decl_iterator
4085 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4086 Decl *D = *I;
4087 if (D->isImplicit()) continue;
4088
4089 // Methods and method templates.
4090 if (isa<CXXMethodDecl>(D)) {
4091 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4092 } else if (isa<FunctionTemplateDecl>(D)) {
4093 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4094 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4095
4096 // Fields and static variables.
4097 } else if (isa<FieldDecl>(D)) {
4098 FieldDecl *FD = cast<FieldDecl>(D);
4099 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4100 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4101 } else if (isa<VarDecl>(D)) {
4102 VarDecl *VD = cast<VarDecl>(D);
4103 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4104 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4105
4106 // Nested classes and class templates.
4107 } else if (isa<CXXRecordDecl>(D)) {
4108 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4109 } else if (isa<ClassTemplateDecl>(D)) {
4110 CheckAbstractClassUsage(Info,
4111 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4112 }
4113 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004114}
4115
Douglas Gregorc99f1552009-12-03 18:33:45 +00004116/// \brief Perform semantic checks on a class definition that has been
4117/// completing, introducing implicitly-declared members, checking for
4118/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004119void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004120 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004121 return;
4122
John McCall02db245d2010-08-18 09:41:07 +00004123 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4124 AbstractUsageInfo Info(*this, Record);
4125 CheckAbstractClassUsage(Info, Record);
4126 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004127
4128 // If this is not an aggregate type and has no user-declared constructor,
4129 // complain about any non-static data members of reference or const scalar
4130 // type, since they will never get initializers.
4131 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004132 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4133 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004134 bool Complained = false;
4135 for (RecordDecl::field_iterator F = Record->field_begin(),
4136 FEnd = Record->field_end();
4137 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004138 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004139 continue;
4140
Douglas Gregor454a5b62010-04-15 00:00:53 +00004141 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004142 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004143 if (!Complained) {
4144 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4145 << Record->getTagKind() << Record;
4146 Complained = true;
4147 }
4148
4149 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4150 << F->getType()->isReferenceType()
4151 << F->getDeclName();
4152 }
4153 }
4154 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004155
Anders Carlssone771e762011-01-25 18:08:22 +00004156 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004157 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004158
4159 if (Record->getIdentifier()) {
4160 // C++ [class.mem]p13:
4161 // If T is the name of a class, then each of the following shall have a
4162 // name different from T:
4163 // - every member of every anonymous union that is a member of class T.
4164 //
4165 // C++ [class.mem]p14:
4166 // In addition, if class T has a user-declared constructor (12.1), every
4167 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004168 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4169 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4170 ++I) {
4171 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004172 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4173 isa<IndirectFieldDecl>(D)) {
4174 Diag(D->getLocation(), diag::err_member_name_of_class)
4175 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004176 break;
4177 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004178 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004179 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004180
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004181 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004182 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004183 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004184 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004185 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4186 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4187 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004188
David Blaikie348df502012-09-21 03:21:07 +00004189 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4190 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4191 DiagnoseAbstractType(Record);
4192 }
4193
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004194 if (!Record->isDependentType()) {
4195 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4196 MEnd = Record->method_end();
4197 M != MEnd; ++M) {
Richard Smithbd305122012-12-11 01:14:52 +00004198 // See if a method overloads virtual methods in a base
4199 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004200 if (!M->isStatic())
David Blaikie40ed2972012-06-06 20:45:41 +00004201 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smithbd305122012-12-11 01:14:52 +00004202
4203 // Check whether the explicitly-defaulted special members are valid.
4204 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4205 CheckExplicitlyDefaultedSpecialMember(*M);
4206
4207 // For an explicitly defaulted or deleted special member, we defer
4208 // determining triviality until the class is complete. That time is now!
4209 if (!M->isImplicit() && !M->isUserProvided()) {
4210 CXXSpecialMember CSM = getSpecialMember(*M);
4211 if (CSM != CXXInvalid) {
4212 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4213
4214 // Inform the class that we've finished declaring this member.
4215 Record->finishedDefaultedOrDeletedMember(*M);
4216 }
4217 }
4218 }
4219 }
4220
4221 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4222 // function that is not a constructor declares that member function to be
4223 // const. [...] The class of which that function is a member shall be
4224 // a literal type.
4225 //
4226 // If the class has virtual bases, any constexpr members will already have
4227 // been diagnosed by the checks performed on the member declaration, so
4228 // suppress this (less useful) diagnostic.
4229 //
4230 // We delay this until we know whether an explicitly-defaulted (or deleted)
4231 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004232 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004233 !Record->isLiteral() && !Record->getNumVBases()) {
4234 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4235 MEnd = Record->method_end();
4236 M != MEnd; ++M) {
4237 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4238 switch (Record->getTemplateSpecializationKind()) {
4239 case TSK_ImplicitInstantiation:
4240 case TSK_ExplicitInstantiationDeclaration:
4241 case TSK_ExplicitInstantiationDefinition:
4242 // If a template instantiates to a non-literal type, but its members
4243 // instantiate to constexpr functions, the template is technically
4244 // ill-formed, but we allow it for sanity.
4245 continue;
4246
4247 case TSK_Undeclared:
4248 case TSK_ExplicitSpecialization:
4249 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4250 diag::err_constexpr_method_non_literal);
4251 break;
4252 }
4253
4254 // Only produce one error per class.
4255 break;
4256 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004257 }
4258 }
Sebastian Redl08905022011-02-05 19:23:19 +00004259
Richard Smithc2bc61b2013-03-18 21:12:30 +00004260 // Declare inheriting constructors. We do this eagerly here because:
4261 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004262 // constructors from different classes.
4263 // - The lazy declaration of the other implicit constructors is so as to not
4264 // waste space and performance on classes that are not meant to be
4265 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004266 // have inheriting constructors.
4267 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004268}
4269
Richard Smithb5800092012-06-10 05:43:50 +00004270/// Is the special member function which would be selected to perform the
4271/// specified operation on the specified class type a constexpr constructor?
4272static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4273 Sema::CXXSpecialMember CSM,
4274 bool ConstArg) {
4275 Sema::SpecialMemberOverloadResult *SMOR =
4276 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4277 false, false, false, false);
4278 if (!SMOR || !SMOR->getMethod())
4279 // A constructor we wouldn't select can't be "involved in initializing"
4280 // anything.
4281 return true;
4282 return SMOR->getMethod()->isConstexpr();
4283}
4284
4285/// Determine whether the specified special member function would be constexpr
4286/// if it were implicitly defined.
4287static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4288 Sema::CXXSpecialMember CSM,
4289 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004290 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004291 return false;
4292
4293 // C++11 [dcl.constexpr]p4:
4294 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004295 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004296 switch (CSM) {
4297 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004298 // Since default constructor lookup is essentially trivial (and cannot
4299 // involve, for instance, template instantiation), we compute whether a
4300 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4301 //
4302 // This is important for performance; we need to know whether the default
4303 // constructor is constexpr to determine whether the type is a literal type.
4304 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4305
Richard Smithb5800092012-06-10 05:43:50 +00004306 case Sema::CXXCopyConstructor:
4307 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004308 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004309 break;
4310
4311 case Sema::CXXCopyAssignment:
4312 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004313 if (!S.getLangOpts().CPlusPlus1y)
4314 return false;
4315 // In C++1y, we need to perform overload resolution.
4316 Ctor = false;
4317 break;
4318
Richard Smithb5800092012-06-10 05:43:50 +00004319 case Sema::CXXDestructor:
4320 case Sema::CXXInvalid:
4321 return false;
4322 }
4323
4324 // -- if the class is a non-empty union, or for each non-empty anonymous
4325 // union member of a non-union class, exactly one non-static data member
4326 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004327 //
4328 // If we squint, this is guaranteed, since exactly one non-static data member
4329 // will be initialized (if the constructor isn't deleted), we just don't know
4330 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004331 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004332 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004333
4334 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004335 if (Ctor && ClassDecl->getNumVBases())
4336 return false;
4337
4338 // C++1y [class.copy]p26:
4339 // -- [the class] is a literal type, and
4340 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004341 return false;
4342
4343 // -- every constructor involved in initializing [...] base class
4344 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004345 // -- the assignment operator selected to copy/move each direct base
4346 // class is a constexpr function, and
Richard Smithb5800092012-06-10 05:43:50 +00004347 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4348 BEnd = ClassDecl->bases_end();
4349 B != BEnd; ++B) {
4350 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4351 if (!BaseType) continue;
4352
4353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4354 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4355 return false;
4356 }
4357
4358 // -- every constructor involved in initializing non-static data members
4359 // [...] shall be a constexpr constructor;
4360 // -- every non-static data member and base class sub-object shall be
4361 // initialized
Richard Smith99005e62013-05-07 03:19:20 +00004362 // -- for each non-stastic data member of X that is of class type (or array
4363 // thereof), the assignment operator selected to copy/move that member is
4364 // a constexpr function
Richard Smithb5800092012-06-10 05:43:50 +00004365 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4366 FEnd = ClassDecl->field_end();
4367 F != FEnd; ++F) {
4368 if (F->isInvalidDecl())
4369 continue;
Richard Smith4086a132012-06-10 07:07:24 +00004370 if (const RecordType *RecordTy =
4371 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004372 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4373 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4374 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004375 }
4376 }
4377
4378 // All OK, it's constexpr!
4379 return true;
4380}
4381
Richard Smithd3b5c9082012-07-27 04:22:15 +00004382static Sema::ImplicitExceptionSpecification
4383computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4384 switch (S.getSpecialMember(MD)) {
4385 case Sema::CXXDefaultConstructor:
4386 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4387 case Sema::CXXCopyConstructor:
4388 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4389 case Sema::CXXCopyAssignment:
4390 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4391 case Sema::CXXMoveConstructor:
4392 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4393 case Sema::CXXMoveAssignment:
4394 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4395 case Sema::CXXDestructor:
4396 return S.ComputeDefaultedDtorExceptionSpec(MD);
4397 case Sema::CXXInvalid:
4398 break;
4399 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004400 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4401 "only special members have implicit exception specs");
4402 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004403}
4404
Richard Smith7f782272012-07-30 23:48:14 +00004405static void
4406updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4407 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4408 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4409 ExceptSpec.getEPI(EPI);
Richard Smith185be182013-04-10 05:48:59 +00004410 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4411 FPT->getArgTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004412}
4413
Richard Smithd3b5c9082012-07-27 04:22:15 +00004414void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4415 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4416 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4417 return;
4418
Richard Smith7f782272012-07-30 23:48:14 +00004419 // Evaluate the exception specification.
4420 ImplicitExceptionSpecification ExceptSpec =
4421 computeImplicitExceptionSpec(*this, Loc, MD);
4422
4423 // Update the type of the special member to use it.
4424 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4425
4426 // A user-provided destructor can be defined outside the class. When that
4427 // happens, be sure to update the exception specification on both
4428 // declarations.
4429 const FunctionProtoType *CanonicalFPT =
4430 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4431 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4432 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4433 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004434}
4435
Richard Smithb9e90b12012-05-15 04:39:51 +00004436void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4437 CXXRecordDecl *RD = MD->getParent();
4438 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004439
Richard Smithb9e90b12012-05-15 04:39:51 +00004440 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4441 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004442
4443 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004444 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004445 bool First = MD == MD->getCanonicalDecl();
4446
4447 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004448
4449 // C++11 [dcl.fct.def.default]p1:
4450 // A function that is explicitly defaulted shall
4451 // -- be a special member function (checked elsewhere),
4452 // -- have the same type (except for ref-qualifiers, and except that a
4453 // copy operation can take a non-const reference) as an implicit
4454 // declaration, and
4455 // -- not have default arguments.
4456 unsigned ExpectedParams = 1;
4457 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4458 ExpectedParams = 0;
4459 if (MD->getNumParams() != ExpectedParams) {
4460 // This also checks for default arguments: a copy or move constructor with a
4461 // default argument is classified as a default constructor, and assignment
4462 // operations and destructors can't have default arguments.
4463 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4464 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004465 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004466 } else if (MD->isVariadic()) {
4467 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4468 << CSM << MD->getSourceRange();
4469 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004470 }
4471
Richard Smithb9e90b12012-05-15 04:39:51 +00004472 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004473
Richard Smithb5800092012-06-10 05:43:50 +00004474 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004475 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004476 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004477 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004478 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004479
Richard Smithb9e90b12012-05-15 04:39:51 +00004480 QualType ReturnType = Context.VoidTy;
4481 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4482 // Check for return type matching.
4483 ReturnType = Type->getResultType();
4484 QualType ExpectedReturnType =
4485 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4486 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4487 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4488 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4489 HadError = true;
4490 }
4491
4492 // A defaulted special member cannot have cv-qualifiers.
4493 if (Type->getTypeQuals()) {
4494 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004495 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004496 HadError = true;
4497 }
4498 }
4499
4500 // Check for parameter type matching.
4501 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004502 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004503 if (ExpectedParams && ArgType->isReferenceType()) {
4504 // Argument must be reference to possibly-const T.
4505 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004506 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004507
4508 if (ReferentType.isVolatileQualified()) {
4509 Diag(MD->getLocation(),
4510 diag::err_defaulted_special_member_volatile_param) << CSM;
4511 HadError = true;
4512 }
4513
Richard Smithb5800092012-06-10 05:43:50 +00004514 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004515 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4516 Diag(MD->getLocation(),
4517 diag::err_defaulted_special_member_copy_const_param)
4518 << (CSM == CXXCopyAssignment);
4519 // FIXME: Explain why this special member can't be const.
4520 } else {
4521 Diag(MD->getLocation(),
4522 diag::err_defaulted_special_member_move_const_param)
4523 << (CSM == CXXMoveAssignment);
4524 }
4525 HadError = true;
4526 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004527 } else if (ExpectedParams) {
4528 // A copy assignment operator can take its argument by value, but a
4529 // defaulted one cannot.
4530 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004531 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004532 HadError = true;
4533 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004534
Richard Smithcc36f692011-12-22 02:22:31 +00004535 // C++11 [dcl.fct.def.default]p2:
4536 // An explicitly-defaulted function may be declared constexpr only if it
4537 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004538 // Do not apply this rule to members of class templates, since core issue 1358
4539 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004540 // functions which cannot be constexpr (for non-constructors in C++11 and for
4541 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004542 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4543 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004544 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4545 : isa<CXXConstructorDecl>(MD)) &&
4546 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004547 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4548 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004549 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004550 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004551 }
Richard Smithbd305122012-12-11 01:14:52 +00004552
Richard Smithcc36f692011-12-22 02:22:31 +00004553 // and may have an explicit exception-specification only if it is compatible
4554 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004555 if (Type->hasExceptionSpec()) {
4556 // Delay the check if this is the first declaration of the special member,
4557 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004558 if (First) {
4559 // If the exception specification needs to be instantiated, do so now,
4560 // before we clobber it with an EST_Unevaluated specification below.
4561 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4562 InstantiateExceptionSpec(MD->getLocStart(), MD);
4563 Type = MD->getType()->getAs<FunctionProtoType>();
4564 }
Richard Smithbd305122012-12-11 01:14:52 +00004565 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004566 } else
Richard Smithbd305122012-12-11 01:14:52 +00004567 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4568 }
Richard Smithcc36f692011-12-22 02:22:31 +00004569
4570 // If a function is explicitly defaulted on its first declaration,
4571 if (First) {
4572 // -- it is implicitly considered to be constexpr if the implicit
4573 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004574 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004575
Richard Smithb9e90b12012-05-15 04:39:51 +00004576 // -- it is implicitly considered to have the same exception-specification
4577 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004578 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4579 EPI.ExceptionSpecType = EST_Unevaluated;
4580 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004581 MD->setType(Context.getFunctionType(ReturnType,
4582 ArrayRef<QualType>(&ArgType,
4583 ExpectedParams),
4584 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004585 }
4586
Richard Smithb9e90b12012-05-15 04:39:51 +00004587 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004588 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004589 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004590 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004591 // C++11 [dcl.fct.def.default]p4:
4592 // [For a] user-provided explicitly-defaulted function [...] if such a
4593 // function is implicitly defined as deleted, the program is ill-formed.
4594 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4595 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004596 }
4597 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004598
Richard Smithb9e90b12012-05-15 04:39:51 +00004599 if (HadError)
4600 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004601}
4602
Richard Smithbd305122012-12-11 01:14:52 +00004603/// Check whether the exception specification provided for an
4604/// explicitly-defaulted special member matches the exception specification
4605/// that would have been generated for an implicit special member, per
4606/// C++11 [dcl.fct.def.default]p2.
4607void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4608 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4609 // Compute the implicit exception specification.
4610 FunctionProtoType::ExtProtoInfo EPI;
4611 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4612 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004613 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004614
4615 // Ensure that it matches.
4616 CheckEquivalentExceptionSpec(
4617 PDiag(diag::err_incorrect_defaulted_exception_spec)
4618 << getSpecialMember(MD), PDiag(),
4619 ImplicitType, SourceLocation(),
4620 SpecifiedType, MD->getLocation());
4621}
4622
4623void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4624 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4625 I != N; ++I)
4626 CheckExplicitlyDefaultedMemberExceptionSpec(
4627 DelayedDefaultedMemberExceptionSpecs[I].first,
4628 DelayedDefaultedMemberExceptionSpecs[I].second);
4629
4630 DelayedDefaultedMemberExceptionSpecs.clear();
4631}
4632
Richard Smithd951a1d2012-02-18 02:02:13 +00004633namespace {
4634struct SpecialMemberDeletionInfo {
4635 Sema &S;
4636 CXXMethodDecl *MD;
4637 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004638 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004639
4640 // Properties of the special member, computed for convenience.
4641 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4642 SourceLocation Loc;
4643
4644 bool AllFieldsAreConst;
4645
4646 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004647 Sema::CXXSpecialMember CSM, bool Diagnose)
4648 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004649 IsConstructor(false), IsAssignment(false), IsMove(false),
4650 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4651 AllFieldsAreConst(true) {
4652 switch (CSM) {
4653 case Sema::CXXDefaultConstructor:
4654 case Sema::CXXCopyConstructor:
4655 IsConstructor = true;
4656 break;
4657 case Sema::CXXMoveConstructor:
4658 IsConstructor = true;
4659 IsMove = true;
4660 break;
4661 case Sema::CXXCopyAssignment:
4662 IsAssignment = true;
4663 break;
4664 case Sema::CXXMoveAssignment:
4665 IsAssignment = true;
4666 IsMove = true;
4667 break;
4668 case Sema::CXXDestructor:
4669 break;
4670 case Sema::CXXInvalid:
4671 llvm_unreachable("invalid special member kind");
4672 }
4673
4674 if (MD->getNumParams()) {
4675 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4676 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4677 }
4678 }
4679
4680 bool inUnion() const { return MD->getParent()->isUnion(); }
4681
4682 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004683 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4684 unsigned Quals) {
Richard Smithd951a1d2012-02-18 02:02:13 +00004685 unsigned TQ = MD->getTypeQualifiers();
Richard Smithaf136f82012-07-18 03:51:16 +00004686 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4687 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4688 Quals = 0;
4689 return S.LookupSpecialMember(Class, CSM,
4690 ConstArg || (Quals & Qualifiers::Const),
4691 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smithd951a1d2012-02-18 02:02:13 +00004692 MD->getRefQualifier() == RQ_RValue,
4693 TQ & Qualifiers::Const,
4694 TQ & Qualifiers::Volatile);
4695 }
4696
Richard Smith852265f2012-03-30 20:53:28 +00004697 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004698
Richard Smith852265f2012-03-30 20:53:28 +00004699 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004700 bool shouldDeleteForField(FieldDecl *FD);
4701 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004702
Richard Smithaf136f82012-07-18 03:51:16 +00004703 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4704 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004705 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4706 Sema::SpecialMemberOverloadResult *SMOR,
4707 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004708
4709 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004710};
4711}
4712
John McCalld4274212012-04-09 20:53:23 +00004713/// Is the given special member inaccessible when used on the given
4714/// sub-object.
4715bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4716 CXXMethodDecl *target) {
4717 /// If we're operating on a base class, the object type is the
4718 /// type of this special member.
4719 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004720 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00004721 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4722 objectTy = S.Context.getTypeDeclType(MD->getParent());
4723 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4724
4725 // If we're operating on a field, the object type is the type of the field.
4726 } else {
4727 objectTy = S.Context.getTypeDeclType(target->getParent());
4728 }
4729
4730 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4731}
4732
Richard Smith852265f2012-03-30 20:53:28 +00004733/// Check whether we should delete a special member due to the implicit
4734/// definition containing a call to a special member of a subobject.
4735bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4736 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4737 bool IsDtorCallInCtor) {
4738 CXXMethodDecl *Decl = SMOR->getMethod();
4739 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4740
4741 int DiagKind = -1;
4742
4743 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4744 DiagKind = !Decl ? 0 : 1;
4745 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4746 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00004747 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00004748 DiagKind = 3;
4749 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4750 !Decl->isTrivial()) {
4751 // A member of a union must have a trivial corresponding special member.
4752 // As a weird special case, a destructor call from a union's constructor
4753 // must be accessible and non-deleted, but need not be trivial. Such a
4754 // destructor is never actually called, but is semantically checked as
4755 // if it were.
4756 DiagKind = 4;
4757 }
4758
4759 if (DiagKind == -1)
4760 return false;
4761
4762 if (Diagnose) {
4763 if (Field) {
4764 S.Diag(Field->getLocation(),
4765 diag::note_deleted_special_member_class_subobject)
4766 << CSM << MD->getParent() << /*IsField*/true
4767 << Field << DiagKind << IsDtorCallInCtor;
4768 } else {
4769 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4770 S.Diag(Base->getLocStart(),
4771 diag::note_deleted_special_member_class_subobject)
4772 << CSM << MD->getParent() << /*IsField*/false
4773 << Base->getType() << DiagKind << IsDtorCallInCtor;
4774 }
4775
4776 if (DiagKind == 1)
4777 S.NoteDeletedFunction(Decl);
4778 // FIXME: Explain inaccessibility if DiagKind == 3.
4779 }
4780
4781 return true;
4782}
4783
Richard Smith921bd202012-02-26 09:11:52 +00004784/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00004785/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00004786bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00004787 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00004788 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smithd951a1d2012-02-18 02:02:13 +00004789
4790 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00004791 // -- any direct or virtual base class, or non-static data member with no
4792 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00004793 // either M has no default constructor or overload resolution as applied
4794 // to M's default constructor results in an ambiguity or in a function
4795 // that is deleted or inaccessible
4796 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4797 // -- a direct or virtual base class B that cannot be copied/moved because
4798 // overload resolution, as applied to B's corresponding special member,
4799 // results in an ambiguity or a function that is deleted or inaccessible
4800 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00004801 // C++11 [class.dtor]p5:
4802 // -- any direct or virtual base class [...] has a type with a destructor
4803 // that is deleted or inaccessible
4804 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00004805 Field && Field->hasInClassInitializer()) &&
Richard Smithaf136f82012-07-18 03:51:16 +00004806 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00004807 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00004808
Richard Smith852265f2012-03-30 20:53:28 +00004809 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4810 // -- any direct or virtual base class or non-static data member has a
4811 // type with a destructor that is deleted or inaccessible
4812 if (IsConstructor) {
4813 Sema::SpecialMemberOverloadResult *SMOR =
4814 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4815 false, false, false, false, false);
4816 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4817 return true;
4818 }
4819
Richard Smith921bd202012-02-26 09:11:52 +00004820 return false;
4821}
4822
4823/// Check whether we should delete a special member function due to the class
4824/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00004825bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00004826 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00004827 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00004828}
4829
4830/// Check whether we should delete a special member function due to the class
4831/// having a particular non-static data member.
4832bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4833 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4834 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4835
4836 if (CSM == Sema::CXXDefaultConstructor) {
4837 // For a default constructor, all references must be initialized in-class
4838 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00004839 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4840 if (Diagnose)
4841 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4842 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00004843 return true;
Richard Smith852265f2012-03-30 20:53:28 +00004844 }
Richard Smith619ecdc2012-02-27 06:07:25 +00004845 // C++11 [class.ctor]p5: any non-variant non-static data member of
4846 // const-qualified type (or array thereof) with no
4847 // brace-or-equal-initializer does not have a user-provided default
4848 // constructor.
4849 if (!inUnion() && FieldType.isConstQualified() &&
4850 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00004851 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4852 if (Diagnose)
4853 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00004854 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00004855 return true;
Richard Smith852265f2012-03-30 20:53:28 +00004856 }
4857
4858 if (inUnion() && !FieldType.isConstQualified())
4859 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00004860 } else if (CSM == Sema::CXXCopyConstructor) {
4861 // For a copy constructor, data members must not be of rvalue reference
4862 // type.
Richard Smith852265f2012-03-30 20:53:28 +00004863 if (FieldType->isRValueReferenceType()) {
4864 if (Diagnose)
4865 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4866 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00004867 return true;
Richard Smith852265f2012-03-30 20:53:28 +00004868 }
Richard Smithd951a1d2012-02-18 02:02:13 +00004869 } else if (IsAssignment) {
4870 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00004871 if (FieldType->isReferenceType()) {
4872 if (Diagnose)
4873 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4874 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00004875 return true;
Richard Smith852265f2012-03-30 20:53:28 +00004876 }
4877 if (!FieldRecord && FieldType.isConstQualified()) {
4878 // C++11 [class.copy]p23:
4879 // -- a non-static data member of const non-class type (or array thereof)
4880 if (Diagnose)
4881 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00004882 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00004883 return true;
4884 }
Richard Smithd951a1d2012-02-18 02:02:13 +00004885 }
4886
4887 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00004888 // Some additional restrictions exist on the variant members.
4889 if (!inUnion() && FieldRecord->isUnion() &&
4890 FieldRecord->isAnonymousStructOrUnion()) {
4891 bool AllVariantFieldsAreConst = true;
4892
Richard Smith5704fe82012-03-29 19:00:10 +00004893 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smithd951a1d2012-02-18 02:02:13 +00004894 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4895 UE = FieldRecord->field_end();
4896 UI != UE; ++UI) {
4897 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00004898
4899 if (!UnionFieldType.isConstQualified())
4900 AllVariantFieldsAreConst = false;
4901
Richard Smith921bd202012-02-26 09:11:52 +00004902 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4903 if (UnionFieldRecord &&
Richard Smithaf136f82012-07-18 03:51:16 +00004904 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4905 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00004906 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00004907 }
4908
4909 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00004910 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith852265f2012-03-30 20:53:28 +00004911 FieldRecord->field_begin() != FieldRecord->field_end()) {
4912 if (Diagnose)
4913 S.Diag(FieldRecord->getLocation(),
4914 diag::note_deleted_default_ctor_all_const)
4915 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00004916 return true;
Richard Smith852265f2012-03-30 20:53:28 +00004917 }
Richard Smithd951a1d2012-02-18 02:02:13 +00004918
Richard Smith5704fe82012-03-29 19:00:10 +00004919 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00004920 // This is technically non-conformant, but sanity demands it.
4921 return false;
4922 }
4923
Richard Smithaf136f82012-07-18 03:51:16 +00004924 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4925 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00004926 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00004927 }
4928
4929 return false;
4930}
4931
4932/// C++11 [class.ctor] p5:
4933/// A defaulted default constructor for a class X is defined as deleted if
4934/// X is a union and all of its variant members are of const-qualified type.
4935bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00004936 // This is a silly definition, because it gives an empty union a deleted
4937 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00004938 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4939 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4940 if (Diagnose)
4941 S.Diag(MD->getParent()->getLocation(),
4942 diag::note_deleted_default_ctor_all_const)
4943 << MD->getParent() << /*not anonymous union*/0;
4944 return true;
4945 }
4946 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00004947}
4948
4949/// Determine whether a defaulted special member function should be defined as
4950/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4951/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00004952bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4953 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00004954 if (MD->isInvalidDecl())
4955 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00004956 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00004957 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004958 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004959 return false;
4960
Richard Smithd951a1d2012-02-18 02:02:13 +00004961 // C++11 [expr.lambda.prim]p19:
4962 // The closure type associated with a lambda-expression has a
4963 // deleted (8.4.3) default constructor and a deleted copy
4964 // assignment operator.
4965 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00004966 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4967 if (Diagnose)
4968 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00004969 return true;
Richard Smith852265f2012-03-30 20:53:28 +00004970 }
4971
Richard Smith6f1e2c62012-04-02 20:59:25 +00004972 // For an anonymous struct or union, the copy and assignment special members
4973 // will never be used, so skip the check. For an anonymous union declared at
4974 // namespace scope, the constructor and destructor are used.
4975 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4976 RD->isAnonymousStructOrUnion())
4977 return false;
4978
Richard Smith852265f2012-03-30 20:53:28 +00004979 // C++11 [class.copy]p7, p18:
4980 // If the class definition declares a move constructor or move assignment
4981 // operator, an implicitly declared copy constructor or copy assignment
4982 // operator is defined as deleted.
4983 if (MD->isImplicit() &&
4984 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4985 CXXMethodDecl *UserDeclaredMove = 0;
4986
4987 // In Microsoft mode, a user-declared move only causes the deletion of the
4988 // corresponding copy operation, not both copy operations.
4989 if (RD->hasUserDeclaredMoveConstructor() &&
4990 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4991 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00004992
4993 // Find any user-declared move constructor.
4994 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4995 E = RD->ctor_end(); I != E; ++I) {
4996 if (I->isMoveConstructor()) {
4997 UserDeclaredMove = *I;
4998 break;
4999 }
5000 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005001 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005002 } else if (RD->hasUserDeclaredMoveAssignment() &&
5003 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5004 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005005
5006 // Find any user-declared move assignment operator.
5007 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5008 E = RD->method_end(); I != E; ++I) {
5009 if (I->isMoveAssignmentOperator()) {
5010 UserDeclaredMove = *I;
5011 break;
5012 }
5013 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005014 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005015 }
5016
5017 if (UserDeclaredMove) {
5018 Diag(UserDeclaredMove->getLocation(),
5019 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005020 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005021 << UserDeclaredMove->isMoveAssignmentOperator();
5022 return true;
5023 }
5024 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005025
Richard Smith6f1e2c62012-04-02 20:59:25 +00005026 // Do access control from the special member function
5027 ContextRAII MethodContext(*this, MD);
5028
Richard Smith921bd202012-02-26 09:11:52 +00005029 // C++11 [class.dtor]p5:
5030 // -- for a virtual destructor, lookup of the non-array deallocation function
5031 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005032 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005033 FunctionDecl *OperatorDelete = 0;
5034 DeclarationName Name =
5035 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5036 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005037 OperatorDelete, false)) {
5038 if (Diagnose)
5039 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005040 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005041 }
Richard Smith921bd202012-02-26 09:11:52 +00005042 }
5043
Richard Smith852265f2012-03-30 20:53:28 +00005044 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005045
Alexis Huntea6f0322011-05-11 22:34:38 +00005046 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005047 BE = RD->bases_end(); BI != BE; ++BI)
5048 if (!BI->isVirtual() &&
Richard Smith852265f2012-03-30 20:53:28 +00005049 SMI.shouldDeleteForBase(BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005050 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005051
5052 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005053 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith852265f2012-03-30 20:53:28 +00005054 if (SMI.shouldDeleteForBase(BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005055 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005056
5057 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005058 FE = RD->field_end(); FI != FE; ++FI)
5059 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie40ed2972012-06-06 20:45:41 +00005060 SMI.shouldDeleteForField(*FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005061 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005062
Richard Smithd951a1d2012-02-18 02:02:13 +00005063 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005064 return true;
5065
5066 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005067}
5068
Richard Smith92f241f2012-12-08 02:53:02 +00005069/// Perform lookup for a special member of the specified kind, and determine
5070/// whether it is trivial. If the triviality can be determined without the
5071/// lookup, skip it. This is intended for use when determining whether a
5072/// special member of a containing object is trivial, and thus does not ever
5073/// perform overload resolution for default constructors.
5074///
5075/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5076/// member that was most likely to be intended to be trivial, if any.
5077static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5078 Sema::CXXSpecialMember CSM, unsigned Quals,
5079 CXXMethodDecl **Selected) {
5080 if (Selected)
5081 *Selected = 0;
5082
5083 switch (CSM) {
5084 case Sema::CXXInvalid:
5085 llvm_unreachable("not a special member");
5086
5087 case Sema::CXXDefaultConstructor:
5088 // C++11 [class.ctor]p5:
5089 // A default constructor is trivial if:
5090 // - all the [direct subobjects] have trivial default constructors
5091 //
5092 // Note, no overload resolution is performed in this case.
5093 if (RD->hasTrivialDefaultConstructor())
5094 return true;
5095
5096 if (Selected) {
5097 // If there's a default constructor which could have been trivial, dig it
5098 // out. Otherwise, if there's any user-provided default constructor, point
5099 // to that as an example of why there's not a trivial one.
5100 CXXConstructorDecl *DefCtor = 0;
5101 if (RD->needsImplicitDefaultConstructor())
5102 S.DeclareImplicitDefaultConstructor(RD);
5103 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5104 CE = RD->ctor_end(); CI != CE; ++CI) {
5105 if (!CI->isDefaultConstructor())
5106 continue;
5107 DefCtor = *CI;
5108 if (!DefCtor->isUserProvided())
5109 break;
5110 }
5111
5112 *Selected = DefCtor;
5113 }
5114
5115 return false;
5116
5117 case Sema::CXXDestructor:
5118 // C++11 [class.dtor]p5:
5119 // A destructor is trivial if:
5120 // - all the direct [subobjects] have trivial destructors
5121 if (RD->hasTrivialDestructor())
5122 return true;
5123
5124 if (Selected) {
5125 if (RD->needsImplicitDestructor())
5126 S.DeclareImplicitDestructor(RD);
5127 *Selected = RD->getDestructor();
5128 }
5129
5130 return false;
5131
5132 case Sema::CXXCopyConstructor:
5133 // C++11 [class.copy]p12:
5134 // A copy constructor is trivial if:
5135 // - the constructor selected to copy each direct [subobject] is trivial
5136 if (RD->hasTrivialCopyConstructor()) {
5137 if (Quals == Qualifiers::Const)
5138 // We must either select the trivial copy constructor or reach an
5139 // ambiguity; no need to actually perform overload resolution.
5140 return true;
5141 } else if (!Selected) {
5142 return false;
5143 }
5144 // In C++98, we are not supposed to perform overload resolution here, but we
5145 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5146 // cases like B as having a non-trivial copy constructor:
5147 // struct A { template<typename T> A(T&); };
5148 // struct B { mutable A a; };
5149 goto NeedOverloadResolution;
5150
5151 case Sema::CXXCopyAssignment:
5152 // C++11 [class.copy]p25:
5153 // A copy assignment operator is trivial if:
5154 // - the assignment operator selected to copy each direct [subobject] is
5155 // trivial
5156 if (RD->hasTrivialCopyAssignment()) {
5157 if (Quals == Qualifiers::Const)
5158 return true;
5159 } else if (!Selected) {
5160 return false;
5161 }
5162 // In C++98, we are not supposed to perform overload resolution here, but we
5163 // treat that as a language defect.
5164 goto NeedOverloadResolution;
5165
5166 case Sema::CXXMoveConstructor:
5167 case Sema::CXXMoveAssignment:
5168 NeedOverloadResolution:
5169 Sema::SpecialMemberOverloadResult *SMOR =
5170 S.LookupSpecialMember(RD, CSM,
5171 Quals & Qualifiers::Const,
5172 Quals & Qualifiers::Volatile,
5173 /*RValueThis*/false, /*ConstThis*/false,
5174 /*VolatileThis*/false);
5175
5176 // The standard doesn't describe how to behave if the lookup is ambiguous.
5177 // We treat it as not making the member non-trivial, just like the standard
5178 // mandates for the default constructor. This should rarely matter, because
5179 // the member will also be deleted.
5180 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5181 return true;
5182
5183 if (!SMOR->getMethod()) {
5184 assert(SMOR->getKind() ==
5185 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5186 return false;
5187 }
5188
5189 // We deliberately don't check if we found a deleted special member. We're
5190 // not supposed to!
5191 if (Selected)
5192 *Selected = SMOR->getMethod();
5193 return SMOR->getMethod()->isTrivial();
5194 }
5195
5196 llvm_unreachable("unknown special method kind");
5197}
5198
Benjamin Kramer3e350262013-02-15 12:30:38 +00005199static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smith92f241f2012-12-08 02:53:02 +00005200 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5201 CI != CE; ++CI)
5202 if (!CI->isImplicit())
5203 return *CI;
5204
5205 // Look for constructor templates.
5206 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5207 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5208 if (CXXConstructorDecl *CD =
5209 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5210 return CD;
5211 }
5212
5213 return 0;
5214}
5215
5216/// The kind of subobject we are checking for triviality. The values of this
5217/// enumeration are used in diagnostics.
5218enum TrivialSubobjectKind {
5219 /// The subobject is a base class.
5220 TSK_BaseClass,
5221 /// The subobject is a non-static data member.
5222 TSK_Field,
5223 /// The object is actually the complete object.
5224 TSK_CompleteObject
5225};
5226
5227/// Check whether the special member selected for a given type would be trivial.
5228static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5229 QualType SubType,
5230 Sema::CXXSpecialMember CSM,
5231 TrivialSubobjectKind Kind,
5232 bool Diagnose) {
5233 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5234 if (!SubRD)
5235 return true;
5236
5237 CXXMethodDecl *Selected;
5238 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5239 Diagnose ? &Selected : 0))
5240 return true;
5241
5242 if (Diagnose) {
5243 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5244 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5245 << Kind << SubType.getUnqualifiedType();
5246 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5247 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5248 } else if (!Selected)
5249 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5250 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5251 else if (Selected->isUserProvided()) {
5252 if (Kind == TSK_CompleteObject)
5253 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5254 << Kind << SubType.getUnqualifiedType() << CSM;
5255 else {
5256 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5257 << Kind << SubType.getUnqualifiedType() << CSM;
5258 S.Diag(Selected->getLocation(), diag::note_declared_at);
5259 }
5260 } else {
5261 if (Kind != TSK_CompleteObject)
5262 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5263 << Kind << SubType.getUnqualifiedType() << CSM;
5264
5265 // Explain why the defaulted or deleted special member isn't trivial.
5266 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5267 }
5268 }
5269
5270 return false;
5271}
5272
5273/// Check whether the members of a class type allow a special member to be
5274/// trivial.
5275static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5276 Sema::CXXSpecialMember CSM,
5277 bool ConstArg, bool Diagnose) {
5278 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5279 FE = RD->field_end(); FI != FE; ++FI) {
5280 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5281 continue;
5282
5283 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5284
5285 // Pretend anonymous struct or union members are members of this class.
5286 if (FI->isAnonymousStructOrUnion()) {
5287 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5288 CSM, ConstArg, Diagnose))
5289 return false;
5290 continue;
5291 }
5292
5293 // C++11 [class.ctor]p5:
5294 // A default constructor is trivial if [...]
5295 // -- no non-static data member of its class has a
5296 // brace-or-equal-initializer
5297 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5298 if (Diagnose)
5299 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5300 return false;
5301 }
5302
5303 // Objective C ARC 4.3.5:
5304 // [...] nontrivally ownership-qualified types are [...] not trivially
5305 // default constructible, copy constructible, move constructible, copy
5306 // assignable, move assignable, or destructible [...]
5307 if (S.getLangOpts().ObjCAutoRefCount &&
5308 FieldType.hasNonTrivialObjCLifetime()) {
5309 if (Diagnose)
5310 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5311 << RD << FieldType.getObjCLifetime();
5312 return false;
5313 }
5314
5315 if (ConstArg && !FI->isMutable())
5316 FieldType.addConst();
5317 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5318 TSK_Field, Diagnose))
5319 return false;
5320 }
5321
5322 return true;
5323}
5324
5325/// Diagnose why the specified class does not have a trivial special member of
5326/// the given kind.
5327void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5328 QualType Ty = Context.getRecordType(RD);
5329 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5330 Ty.addConst();
5331
5332 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5333 TSK_CompleteObject, /*Diagnose*/true);
5334}
5335
5336/// Determine whether a defaulted or deleted special member function is trivial,
5337/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5338/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5339bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5340 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005341 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5342
5343 CXXRecordDecl *RD = MD->getParent();
5344
5345 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005346
5347 // C++11 [class.copy]p12, p25:
5348 // A [special member] is trivial if its declared parameter type is the same
5349 // as if it had been implicitly declared [...]
5350 switch (CSM) {
5351 case CXXDefaultConstructor:
5352 case CXXDestructor:
5353 // Trivial default constructors and destructors cannot have parameters.
5354 break;
5355
5356 case CXXCopyConstructor:
5357 case CXXCopyAssignment: {
5358 // Trivial copy operations always have const, non-volatile parameter types.
5359 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005360 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005361 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5362 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5363 if (Diagnose)
5364 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5365 << Param0->getSourceRange() << Param0->getType()
5366 << Context.getLValueReferenceType(
5367 Context.getRecordType(RD).withConst());
5368 return false;
5369 }
5370 break;
5371 }
5372
5373 case CXXMoveConstructor:
5374 case CXXMoveAssignment: {
5375 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005376 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005377 const RValueReferenceType *RT =
5378 Param0->getType()->getAs<RValueReferenceType>();
5379 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5380 if (Diagnose)
5381 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5382 << Param0->getSourceRange() << Param0->getType()
5383 << Context.getRValueReferenceType(Context.getRecordType(RD));
5384 return false;
5385 }
5386 break;
5387 }
5388
5389 case CXXInvalid:
5390 llvm_unreachable("not a special member");
5391 }
5392
5393 // FIXME: We require that the parameter-declaration-clause is equivalent to
5394 // that of an implicit declaration, not just that the declared parameter type
5395 // matches, in order to prevent absuridities like a function simultaneously
5396 // being a trivial copy constructor and a non-trivial default constructor.
5397 // This issue has not yet been assigned a core issue number.
5398 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5399 if (Diagnose)
5400 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5401 diag::note_nontrivial_default_arg)
5402 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5403 return false;
5404 }
5405 if (MD->isVariadic()) {
5406 if (Diagnose)
5407 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5408 return false;
5409 }
5410
5411 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5412 // A copy/move [constructor or assignment operator] is trivial if
5413 // -- the [member] selected to copy/move each direct base class subobject
5414 // is trivial
5415 //
5416 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5417 // A [default constructor or destructor] is trivial if
5418 // -- all the direct base classes have trivial [default constructors or
5419 // destructors]
5420 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5421 BE = RD->bases_end(); BI != BE; ++BI)
5422 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5423 ConstArg ? BI->getType().withConst()
5424 : BI->getType(),
5425 CSM, TSK_BaseClass, Diagnose))
5426 return false;
5427
5428 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5429 // A copy/move [constructor or assignment operator] for a class X is
5430 // trivial if
5431 // -- for each non-static data member of X that is of class type (or array
5432 // thereof), the constructor selected to copy/move that member is
5433 // trivial
5434 //
5435 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5436 // A [default constructor or destructor] is trivial if
5437 // -- for all of the non-static data members of its class that are of class
5438 // type (or array thereof), each such class has a trivial [default
5439 // constructor or destructor]
5440 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5441 return false;
5442
5443 // C++11 [class.dtor]p5:
5444 // A destructor is trivial if [...]
5445 // -- the destructor is not virtual
5446 if (CSM == CXXDestructor && MD->isVirtual()) {
5447 if (Diagnose)
5448 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5449 return false;
5450 }
5451
5452 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5453 // A [special member] for class X is trivial if [...]
5454 // -- class X has no virtual functions and no virtual base classes
5455 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5456 if (!Diagnose)
5457 return false;
5458
5459 if (RD->getNumVBases()) {
5460 // Check for virtual bases. We already know that the corresponding
5461 // member in all bases is trivial, so vbases must all be direct.
5462 CXXBaseSpecifier &BS = *RD->vbases_begin();
5463 assert(BS.isVirtual());
5464 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5465 return false;
5466 }
5467
5468 // Must have a virtual method.
5469 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5470 ME = RD->method_end(); MI != ME; ++MI) {
5471 if (MI->isVirtual()) {
5472 SourceLocation MLoc = MI->getLocStart();
5473 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5474 return false;
5475 }
5476 }
5477
5478 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5479 }
5480
5481 // Looks like it's trivial!
5482 return true;
5483}
5484
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005485/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005486namespace {
5487 struct FindHiddenVirtualMethodData {
5488 Sema *S;
5489 CXXMethodDecl *Method;
5490 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005491 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005492 };
5493}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005494
David Blaikie282c92a2012-10-19 00:53:08 +00005495/// \brief Check whether any most overriden method from MD in Methods
5496static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5497 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5498 if (MD->size_overridden_methods() == 0)
5499 return Methods.count(MD->getCanonicalDecl());
5500 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5501 E = MD->end_overridden_methods();
5502 I != E; ++I)
5503 if (CheckMostOverridenMethods(*I, Methods))
5504 return true;
5505 return false;
5506}
5507
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005508/// \brief Member lookup function that determines whether a given C++
5509/// method overloads virtual methods in a base class without overriding any,
5510/// to be used with CXXRecordDecl::lookupInBases().
5511static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5512 CXXBasePath &Path,
5513 void *UserData) {
5514 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5515
5516 FindHiddenVirtualMethodData &Data
5517 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5518
5519 DeclarationName Name = Data.Method->getDeclName();
5520 assert(Name.getNameKind() == DeclarationName::Identifier);
5521
5522 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005523 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005524 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005525 !Path.Decls.empty();
5526 Path.Decls = Path.Decls.slice(1)) {
5527 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005528 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005529 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005530 foundSameNameMethod = true;
5531 // Interested only in hidden virtual methods.
5532 if (!MD->isVirtual())
5533 continue;
5534 // If the method we are checking overrides a method from its base
5535 // don't warn about the other overloaded methods.
5536 if (!Data.S->IsOverload(Data.Method, MD, false))
5537 return true;
5538 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005539 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005540 overloadedMethods.push_back(MD);
5541 }
5542 }
5543
5544 if (foundSameNameMethod)
5545 Data.OverloadedMethods.append(overloadedMethods.begin(),
5546 overloadedMethods.end());
5547 return foundSameNameMethod;
5548}
5549
David Blaikie282c92a2012-10-19 00:53:08 +00005550/// \brief Add the most overriden methods from MD to Methods
5551static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5552 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5553 if (MD->size_overridden_methods() == 0)
5554 Methods.insert(MD->getCanonicalDecl());
5555 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5556 E = MD->end_overridden_methods();
5557 I != E; ++I)
5558 AddMostOverridenMethods(*I, Methods);
5559}
5560
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005561/// \brief See if a method overloads virtual methods in a base class without
5562/// overriding any.
5563void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5564 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00005565 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005566 return;
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005567 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005568 return;
5569
5570 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5571 /*bool RecordPaths=*/false,
5572 /*bool DetectVirtual=*/false);
5573 FindHiddenVirtualMethodData Data;
5574 Data.Method = MD;
5575 Data.S = this;
5576
5577 // Keep the base methods that were overriden or introduced in the subclass
5578 // by 'using' in a set. A base method not in this set is hidden.
David Blaikieff7d47a2012-12-19 00:45:41 +00005579 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5580 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5581 NamedDecl *ND = *I;
5582 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005583 ND = shad->getTargetDecl();
5584 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5585 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005586 }
5587
5588 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5589 !Data.OverloadedMethods.empty()) {
5590 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5591 << MD << (Data.OverloadedMethods.size() > 1);
5592
5593 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5594 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieu05c4d022013-04-05 23:02:24 +00005595 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005596 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieu05c4d022013-04-05 23:02:24 +00005597 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5598 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005599 }
5600 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005601}
5602
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005603void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005604 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005605 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005606 SourceLocation RBrac,
5607 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005608 if (!TagDecl)
5609 return;
Mike Stump11289f42009-09-09 15:08:12 +00005610
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005611 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005612
Rafael Espindola06e1b132012-07-12 04:32:30 +00005613 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5614 if (l->getKind() != AttributeList::AT_Visibility)
5615 continue;
5616 l->setInvalid();
5617 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5618 l->getName();
5619 }
5620
David Blaikie751c5582011-09-22 02:58:26 +00005621 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005622 // strict aliasing violation!
5623 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005624 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005625
Douglas Gregor0be31a22010-07-02 17:43:08 +00005626 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005627 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005628}
5629
Douglas Gregor05379422008-11-03 17:51:48 +00005630/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5631/// special functions, such as the default constructor, copy
5632/// constructor, or destructor, to the given C++ class (C++
5633/// [special]p1). This routine can only be executed just before the
5634/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005635void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005636 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005637 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005638
Richard Smith6b02d462012-12-08 08:32:28 +00005639 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005640 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005641
Richard Smith6b02d462012-12-08 08:32:28 +00005642 // If the properties or semantics of the copy constructor couldn't be
5643 // determined while the class was being declared, force a declaration
5644 // of it now.
5645 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5646 DeclareImplicitCopyConstructor(ClassDecl);
5647 }
5648
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005649 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005650 ++ASTContext::NumImplicitMoveConstructors;
5651
Richard Smith6b02d462012-12-08 08:32:28 +00005652 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5653 DeclareImplicitMoveConstructor(ClassDecl);
5654 }
5655
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005656 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5657 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005658
5659 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005660 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005661 // it shows up in the right place in the vtable and that we diagnose
5662 // problems with the implicit exception specification.
5663 if (ClassDecl->isDynamicClass() ||
5664 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005665 DeclareImplicitCopyAssignment(ClassDecl);
5666 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005667
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005668 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005669 ++ASTContext::NumImplicitMoveAssignmentOperators;
5670
5671 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005672 if (ClassDecl->isDynamicClass() ||
5673 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005674 DeclareImplicitMoveAssignment(ClassDecl);
5675 }
5676
Douglas Gregor7454c562010-07-02 20:37:36 +00005677 if (!ClassDecl->hasUserDeclaredDestructor()) {
5678 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005679
5680 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005681 // have to declare the destructor immediately. This ensures that, e.g., it
5682 // shows up in the right place in the vtable and that we diagnose problems
5683 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005684 if (ClassDecl->isDynamicClass() ||
5685 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005686 DeclareImplicitDestructor(ClassDecl);
5687 }
Douglas Gregor05379422008-11-03 17:51:48 +00005688}
5689
Francois Pichet1c229c02011-04-22 22:18:13 +00005690void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5691 if (!D)
5692 return;
5693
5694 int NumParamList = D->getNumTemplateParameterLists();
5695 for (int i = 0; i < NumParamList; i++) {
5696 TemplateParameterList* Params = D->getTemplateParameterList(i);
5697 for (TemplateParameterList::iterator Param = Params->begin(),
5698 ParamEnd = Params->end();
5699 Param != ParamEnd; ++Param) {
5700 NamedDecl *Named = cast<NamedDecl>(*Param);
5701 if (Named->getDeclName()) {
5702 S->AddDecl(Named);
5703 IdResolver.AddDecl(Named);
5704 }
5705 }
5706 }
5707}
5708
John McCall48871652010-08-21 09:40:31 +00005709void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005710 if (!D)
5711 return;
5712
5713 TemplateParameterList *Params = 0;
5714 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5715 Params = Template->getTemplateParameters();
5716 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5717 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5718 Params = PartialSpec->getTemplateParameters();
5719 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005720 return;
5721
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005722 for (TemplateParameterList::iterator Param = Params->begin(),
5723 ParamEnd = Params->end();
5724 Param != ParamEnd; ++Param) {
5725 NamedDecl *Named = cast<NamedDecl>(*Param);
5726 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005727 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005728 IdResolver.AddDecl(Named);
5729 }
5730 }
5731}
5732
John McCall48871652010-08-21 09:40:31 +00005733void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005734 if (!RecordD) return;
5735 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005736 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005737 PushDeclContext(S, Record);
5738}
5739
John McCall48871652010-08-21 09:40:31 +00005740void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005741 if (!RecordD) return;
5742 PopDeclContext();
5743}
5744
Douglas Gregor4d87df52008-12-16 21:30:33 +00005745/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5746/// parsing a top-level (non-nested) C++ class, and we are now
5747/// parsing those parts of the given Method declaration that could
5748/// not be parsed earlier (C++ [class.mem]p2), such as default
5749/// arguments. This action should enter the scope of the given
5750/// Method declaration as if we had just parsed the qualified method
5751/// name. However, it should not bring the parameters into scope;
5752/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005753void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005754}
5755
5756/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5757/// C++ method declaration. We're (re-)introducing the given
5758/// function parameter into scope for use in parsing later parts of
5759/// the method declaration. For example, we could see an
5760/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00005761void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005762 if (!ParamD)
5763 return;
Mike Stump11289f42009-09-09 15:08:12 +00005764
John McCall48871652010-08-21 09:40:31 +00005765 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00005766
5767 // If this parameter has an unparsed default argument, clear it out
5768 // to make way for the parsed default argument.
5769 if (Param->hasUnparsedDefaultArg())
5770 Param->setDefaultArg(0);
5771
John McCall48871652010-08-21 09:40:31 +00005772 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005773 if (Param->getDeclName())
5774 IdResolver.AddDecl(Param);
5775}
5776
5777/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5778/// processing the delayed method declaration for Method. The method
5779/// declaration is now considered finished. There may be a separate
5780/// ActOnStartOfFunctionDef action later (not necessarily
5781/// immediately!) for this method, if it was also defined inside the
5782/// class body.
John McCall48871652010-08-21 09:40:31 +00005783void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005784 if (!MethodD)
5785 return;
Mike Stump11289f42009-09-09 15:08:12 +00005786
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005787 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005788
John McCall48871652010-08-21 09:40:31 +00005789 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005790
5791 // Now that we have our default arguments, check the constructor
5792 // again. It could produce additional diagnostics or affect whether
5793 // the class has implicitly-declared destructors, among other
5794 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005795 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5796 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005797
5798 // Check the default arguments, which we may have added.
5799 if (!Method->isInvalidDecl())
5800 CheckCXXDefaultArguments(Method);
5801}
5802
Douglas Gregor831c93f2008-11-05 20:51:48 +00005803/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005804/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005805/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005806/// emit diagnostics and set the invalid bit to true. In any case, the type
5807/// will be updated to reflect a well-formed type for the constructor and
5808/// returned.
5809QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005810 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005811 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005812
5813 // C++ [class.ctor]p3:
5814 // A constructor shall not be virtual (10.3) or static (9.4). A
5815 // constructor can be invoked for a const, volatile or const
5816 // volatile object. A constructor shall not be declared const,
5817 // volatile, or const volatile (9.3.2).
5818 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005819 if (!D.isInvalidType())
5820 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5821 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5822 << SourceRange(D.getIdentifierLoc());
5823 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005824 }
John McCall8e7d6562010-08-26 03:08:43 +00005825 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005826 if (!D.isInvalidType())
5827 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5828 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5829 << SourceRange(D.getIdentifierLoc());
5830 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005831 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005832 }
Mike Stump11289f42009-09-09 15:08:12 +00005833
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005834 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005835 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005836 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005837 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5838 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005839 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005840 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5841 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005842 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005843 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5844 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005845 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005846 }
Mike Stump11289f42009-09-09 15:08:12 +00005847
Douglas Gregordb9d6642011-01-26 05:01:58 +00005848 // C++0x [class.ctor]p4:
5849 // A constructor shall not be declared with a ref-qualifier.
5850 if (FTI.hasRefQualifier()) {
5851 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5852 << FTI.RefQualifierIsLValueRef
5853 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5854 D.setInvalidType();
5855 }
5856
Douglas Gregor831c93f2008-11-05 20:51:48 +00005857 // Rebuild the function type "R" without any type qualifiers (in
5858 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005859 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005860 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005861 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5862 return R;
5863
5864 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5865 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005866 EPI.RefQualifier = RQ_None;
5867
Richard Smithc2bc61b2013-03-18 21:12:30 +00005868 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005869}
5870
Douglas Gregor4d87df52008-12-16 21:30:33 +00005871/// CheckConstructor - Checks a fully-formed constructor for
5872/// well-formedness, issuing any diagnostics required. Returns true if
5873/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005874void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005875 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005876 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5877 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005878 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005879
5880 // C++ [class.copy]p3:
5881 // A declaration of a constructor for a class X is ill-formed if
5882 // its first parameter is of type (optionally cv-qualified) X and
5883 // either there are no other parameters or else all other
5884 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005885 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005886 ((Constructor->getNumParams() == 1) ||
5887 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005888 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5889 Constructor->getTemplateSpecializationKind()
5890 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005891 QualType ParamType = Constructor->getParamDecl(0)->getType();
5892 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5893 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005894 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005895 const char *ConstRef
5896 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5897 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005898 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005899 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005900
5901 // FIXME: Rather that making the constructor invalid, we should endeavor
5902 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005903 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005904 }
5905 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005906}
5907
John McCalldeb646e2010-08-04 01:04:25 +00005908/// CheckDestructor - Checks a fully-formed destructor definition for
5909/// well-formedness, issuing any diagnostics required. Returns true
5910/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005911bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005912 CXXRecordDecl *RD = Destructor->getParent();
5913
Peter Collingbourneb289fe62013-05-20 14:12:25 +00005914 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005915 SourceLocation Loc;
5916
5917 if (!Destructor->isImplicit())
5918 Loc = Destructor->getLocation();
5919 else
5920 Loc = RD->getLocation();
5921
5922 // If we have a virtual destructor, look up the deallocation function
5923 FunctionDecl *OperatorDelete = 0;
5924 DeclarationName Name =
5925 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005926 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005927 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005928
Eli Friedmanfa0df832012-02-02 03:46:19 +00005929 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005930
5931 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005932 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005933
5934 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005935}
5936
Mike Stump11289f42009-09-09 15:08:12 +00005937static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005938FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5939 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5940 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005941 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005942}
5943
Douglas Gregor831c93f2008-11-05 20:51:48 +00005944/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5945/// the well-formednes of the destructor declarator @p D with type @p
5946/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005947/// emit diagnostics and set the declarator to invalid. Even if this happens,
5948/// will be updated to reflect a well-formed type for the destructor and
5949/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005950QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005951 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005952 // C++ [class.dtor]p1:
5953 // [...] A typedef-name that names a class is a class-name
5954 // (7.1.3); however, a typedef-name that names a class shall not
5955 // be used as the identifier in the declarator for a destructor
5956 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005957 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005958 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005959 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005960 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005961 else if (const TemplateSpecializationType *TST =
5962 DeclaratorType->getAs<TemplateSpecializationType>())
5963 if (TST->isTypeAlias())
5964 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5965 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005966
5967 // C++ [class.dtor]p2:
5968 // A destructor is used to destroy objects of its class type. A
5969 // destructor takes no parameters, and no return type can be
5970 // specified for it (not even void). The address of a destructor
5971 // shall not be taken. A destructor shall not be static. A
5972 // destructor can be invoked for a const, volatile or const
5973 // volatile object. A destructor shall not be declared const,
5974 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005975 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005976 if (!D.isInvalidType())
5977 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5978 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005979 << SourceRange(D.getIdentifierLoc())
5980 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5981
John McCall8e7d6562010-08-26 03:08:43 +00005982 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005983 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005984 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005985 // Destructors don't have return types, but the parser will
5986 // happily parse something like:
5987 //
5988 // class X {
5989 // float ~X();
5990 // };
5991 //
5992 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005993 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5994 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5995 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005996 }
Mike Stump11289f42009-09-09 15:08:12 +00005997
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005998 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005999 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006000 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006001 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6002 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006003 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006004 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6005 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006006 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006007 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6008 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006009 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006010 }
6011
Douglas Gregordb9d6642011-01-26 05:01:58 +00006012 // C++0x [class.dtor]p2:
6013 // A destructor shall not be declared with a ref-qualifier.
6014 if (FTI.hasRefQualifier()) {
6015 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6016 << FTI.RefQualifierIsLValueRef
6017 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6018 D.setInvalidType();
6019 }
6020
Douglas Gregor831c93f2008-11-05 20:51:48 +00006021 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00006022 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006023 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6024
6025 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00006026 FTI.freeArgs();
6027 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006028 }
6029
Mike Stump11289f42009-09-09 15:08:12 +00006030 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006031 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006032 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006033 D.setInvalidType();
6034 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006035
6036 // Rebuild the function type "R" without any type qualifiers or
6037 // parameters (in case any of the errors above fired) and with
6038 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006039 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006040 if (!D.isInvalidType())
6041 return R;
6042
Douglas Gregor95755162010-07-01 05:10:53 +00006043 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006044 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6045 EPI.Variadic = false;
6046 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006047 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006048 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006049}
6050
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006051/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6052/// well-formednes of the conversion function declarator @p D with
6053/// type @p R. If there are any errors in the declarator, this routine
6054/// will emit diagnostics and return true. Otherwise, it will return
6055/// false. Either way, the type @p R will be updated to reflect a
6056/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006057void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006058 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006059 // C++ [class.conv.fct]p1:
6060 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006061 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006062 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006063 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006064 if (!D.isInvalidType())
6065 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006066 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6067 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006068 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006069 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006070 }
John McCall212fa2e2010-04-13 00:04:31 +00006071
6072 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6073
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006074 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006075 // Conversion functions don't have return types, but the parser will
6076 // happily parse something like:
6077 //
6078 // class X {
6079 // float operator bool();
6080 // };
6081 //
6082 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006083 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6084 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6085 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006086 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006087 }
6088
John McCall212fa2e2010-04-13 00:04:31 +00006089 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6090
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006091 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00006092 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006093 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6094
6095 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006096 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006097 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006098 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006099 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006100 D.setInvalidType();
6101 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006102
John McCall212fa2e2010-04-13 00:04:31 +00006103 // Diagnose "&operator bool()" and other such nonsense. This
6104 // is actually a gcc extension which we don't support.
6105 if (Proto->getResultType() != ConvType) {
6106 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6107 << Proto->getResultType();
6108 D.setInvalidType();
6109 ConvType = Proto->getResultType();
6110 }
6111
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006112 // C++ [class.conv.fct]p4:
6113 // The conversion-type-id shall not represent a function type nor
6114 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006115 if (ConvType->isArrayType()) {
6116 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6117 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006118 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006119 } else if (ConvType->isFunctionType()) {
6120 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6121 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006122 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006123 }
6124
6125 // Rebuild the function type "R" without any parameters (in case any
6126 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006127 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006128 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006129 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006130
Douglas Gregor5fb53972009-01-14 15:45:31 +00006131 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006132 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006133 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006134 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006135 diag::warn_cxx98_compat_explicit_conversion_functions :
6136 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006137 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006138}
6139
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006140/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6141/// the declaration of the given C++ conversion function. This routine
6142/// is responsible for recording the conversion function in the C++
6143/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006144Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006145 assert(Conversion && "Expected to receive a conversion function declaration");
6146
Douglas Gregor4287b372008-12-12 08:25:50 +00006147 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006148
6149 // Make sure we aren't redeclaring the conversion function.
6150 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006151
6152 // C++ [class.conv.fct]p1:
6153 // [...] A conversion function is never used to convert a
6154 // (possibly cv-qualified) object to the (possibly cv-qualified)
6155 // same object type (or a reference to it), to a (possibly
6156 // cv-qualified) base class of that type (or a reference to it),
6157 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006158 // FIXME: Suppress this warning if the conversion function ends up being a
6159 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006160 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006161 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006162 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006163 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006164 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6165 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006166 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006167 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006168 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6169 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006170 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006171 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006172 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006173 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006174 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006175 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006176 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006177 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006178 }
6179
Douglas Gregor457104e2010-09-29 04:25:11 +00006180 if (FunctionTemplateDecl *ConversionTemplate
6181 = Conversion->getDescribedFunctionTemplate())
6182 return ConversionTemplate;
6183
John McCall48871652010-08-21 09:40:31 +00006184 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006185}
6186
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006187//===----------------------------------------------------------------------===//
6188// Namespace Handling
6189//===----------------------------------------------------------------------===//
6190
Richard Smith45bb8852012-10-04 22:13:39 +00006191/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6192/// reopened.
6193static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6194 SourceLocation Loc,
6195 IdentifierInfo *II, bool *IsInline,
6196 NamespaceDecl *PrevNS) {
6197 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006198
Richard Smithf501cc32012-10-05 01:46:25 +00006199 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6200 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6201 // inline namespaces, with the intention of bringing names into namespace std.
6202 //
6203 // We support this just well enough to get that case working; this is not
6204 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006205 if (*IsInline && II && II->getName().startswith("__atomic") &&
6206 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006207 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006208 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6209 NS = NS->getPreviousDecl())
6210 NS->setInline(*IsInline);
6211 // Patch up the lookup table for the containing namespace. This isn't really
6212 // correct, but it's good enough for this particular case.
6213 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6214 E = PrevNS->decls_end(); I != E; ++I)
6215 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6216 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6217 return;
6218 }
6219
6220 if (PrevNS->isInline())
6221 // The user probably just forgot the 'inline', so suggest that it
6222 // be added back.
6223 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6224 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6225 else
6226 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6227 << IsInline;
6228
6229 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6230 *IsInline = PrevNS->isInline();
6231}
John McCallb1be5232010-08-26 09:15:37 +00006232
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006233/// ActOnStartNamespaceDef - This is called at the start of a namespace
6234/// definition.
John McCall48871652010-08-21 09:40:31 +00006235Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006236 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006237 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006238 SourceLocation IdentLoc,
6239 IdentifierInfo *II,
6240 SourceLocation LBrace,
6241 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006242 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6243 // For anonymous namespace, take the location of the left brace.
6244 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006245 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006246 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006247 bool IsStd = false;
6248 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006249 Scope *DeclRegionScope = NamespcScope->getParent();
6250
Douglas Gregore57e7522012-01-07 09:11:48 +00006251 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006252 if (II) {
6253 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006254 // The identifier in an original-namespace-definition shall not
6255 // have been previously defined in the declarative region in
6256 // which the original-namespace-definition appears. The
6257 // identifier in an original-namespace-definition is the name of
6258 // the namespace. Subsequently in that declarative region, it is
6259 // treated as an original-namespace-name.
6260 //
6261 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006262 // look through using directives, just look for any ordinary names.
6263
6264 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006265 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6266 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006267 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006268 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6269 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6270 ++I) {
6271 if ((*I)->getIdentifierNamespace() & IDNS) {
6272 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006273 break;
6274 }
6275 }
6276
Douglas Gregore57e7522012-01-07 09:11:48 +00006277 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6278
6279 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006280 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006281 if (IsInline != PrevNS->isInline())
6282 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6283 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006284 } else if (PrevDecl) {
6285 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006286 Diag(Loc, diag::err_redefinition_different_kind)
6287 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006288 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006289 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006290 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006291 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006292 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006293 // This is the first "real" definition of the namespace "std", so update
6294 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006295 PrevNS = getStdNamespace();
6296 IsStd = true;
6297 AddToKnown = !IsInline;
6298 } else {
6299 // We've seen this namespace for the first time.
6300 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006301 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006302 } else {
John McCall4fa53422009-10-01 00:25:31 +00006303 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006304
6305 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006306 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006307 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006308 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006309 } else {
6310 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006311 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006312 }
6313
Richard Smith45bb8852012-10-04 22:13:39 +00006314 if (PrevNS && IsInline != PrevNS->isInline())
6315 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6316 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006317 }
6318
6319 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6320 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006321 if (IsInvalid)
6322 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006323
6324 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006325
Douglas Gregore57e7522012-01-07 09:11:48 +00006326 // FIXME: Should we be merging attributes?
6327 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006328 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006329
6330 if (IsStd)
6331 StdNamespace = Namespc;
6332 if (AddToKnown)
6333 KnownNamespaces[Namespc] = false;
6334
6335 if (II) {
6336 PushOnScopeChains(Namespc, DeclRegionScope);
6337 } else {
6338 // Link the anonymous namespace into its parent.
6339 DeclContext *Parent = CurContext->getRedeclContext();
6340 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6341 TU->setAnonymousNamespace(Namespc);
6342 } else {
6343 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006344 }
John McCall4fa53422009-10-01 00:25:31 +00006345
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006346 CurContext->addDecl(Namespc);
6347
John McCall4fa53422009-10-01 00:25:31 +00006348 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6349 // behaves as if it were replaced by
6350 // namespace unique { /* empty body */ }
6351 // using namespace unique;
6352 // namespace unique { namespace-body }
6353 // where all occurrences of 'unique' in a translation unit are
6354 // replaced by the same identifier and this identifier differs
6355 // from all other identifiers in the entire program.
6356
6357 // We just create the namespace with an empty name and then add an
6358 // implicit using declaration, just like the standard suggests.
6359 //
6360 // CodeGen enforces the "universally unique" aspect by giving all
6361 // declarations semantically contained within an anonymous
6362 // namespace internal linkage.
6363
Douglas Gregore57e7522012-01-07 09:11:48 +00006364 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006365 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006366 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006367 /* 'using' */ LBrace,
6368 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006369 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006370 /* identifier */ SourceLocation(),
6371 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006372 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006373 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006374 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006375 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006376 }
6377
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006378 ActOnDocumentableDecl(Namespc);
6379
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006380 // Although we could have an invalid decl (i.e. the namespace name is a
6381 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006382 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6383 // for the namespace has the declarations that showed up in that particular
6384 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006385 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006386 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006387}
6388
Sebastian Redla6602e92009-11-23 15:34:23 +00006389/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6390/// is a namespace alias, returns the namespace it points to.
6391static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6392 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6393 return AD->getNamespace();
6394 return dyn_cast_or_null<NamespaceDecl>(D);
6395}
6396
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006397/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6398/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006399void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006400 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6401 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006402 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006403 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006404 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006405 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006406}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006407
John McCall28a0cf72010-08-25 07:42:41 +00006408CXXRecordDecl *Sema::getStdBadAlloc() const {
6409 return cast_or_null<CXXRecordDecl>(
6410 StdBadAlloc.get(Context.getExternalSource()));
6411}
6412
6413NamespaceDecl *Sema::getStdNamespace() const {
6414 return cast_or_null<NamespaceDecl>(
6415 StdNamespace.get(Context.getExternalSource()));
6416}
6417
Douglas Gregorcdf87022010-06-29 17:53:46 +00006418/// \brief Retrieve the special "std" namespace, which may require us to
6419/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006420NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006421 if (!StdNamespace) {
6422 // The "std" namespace has not yet been defined, so build one implicitly.
6423 StdNamespace = NamespaceDecl::Create(Context,
6424 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006425 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006426 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006427 &PP.getIdentifierTable().get("std"),
6428 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006429 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006430 }
6431
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006432 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006433}
6434
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006435bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006436 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006437 "Looking for std::initializer_list outside of C++.");
6438
6439 // We're looking for implicit instantiations of
6440 // template <typename E> class std::initializer_list.
6441
6442 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6443 return false;
6444
Sebastian Redl43144e72012-01-17 22:49:58 +00006445 ClassTemplateDecl *Template = 0;
6446 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006447
Sebastian Redl43144e72012-01-17 22:49:58 +00006448 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006449
Sebastian Redl43144e72012-01-17 22:49:58 +00006450 ClassTemplateSpecializationDecl *Specialization =
6451 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6452 if (!Specialization)
6453 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006454
Sebastian Redl43144e72012-01-17 22:49:58 +00006455 Template = Specialization->getSpecializedTemplate();
6456 Arguments = Specialization->getTemplateArgs().data();
6457 } else if (const TemplateSpecializationType *TST =
6458 Ty->getAs<TemplateSpecializationType>()) {
6459 Template = dyn_cast_or_null<ClassTemplateDecl>(
6460 TST->getTemplateName().getAsTemplateDecl());
6461 Arguments = TST->getArgs();
6462 }
6463 if (!Template)
6464 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006465
6466 if (!StdInitializerList) {
6467 // Haven't recognized std::initializer_list yet, maybe this is it.
6468 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6469 if (TemplateClass->getIdentifier() !=
6470 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006471 !getStdNamespace()->InEnclosingNamespaceSetOf(
6472 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006473 return false;
6474 // This is a template called std::initializer_list, but is it the right
6475 // template?
6476 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006477 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006478 return false;
6479 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6480 return false;
6481
6482 // It's the right template.
6483 StdInitializerList = Template;
6484 }
6485
6486 if (Template != StdInitializerList)
6487 return false;
6488
6489 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006490 if (Element)
6491 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006492 return true;
6493}
6494
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006495static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6496 NamespaceDecl *Std = S.getStdNamespace();
6497 if (!Std) {
6498 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6499 return 0;
6500 }
6501
6502 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6503 Loc, Sema::LookupOrdinaryName);
6504 if (!S.LookupQualifiedName(Result, Std)) {
6505 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6506 return 0;
6507 }
6508 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6509 if (!Template) {
6510 Result.suppressDiagnostics();
6511 // We found something weird. Complain about the first thing we found.
6512 NamedDecl *Found = *Result.begin();
6513 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6514 return 0;
6515 }
6516
6517 // We found some template called std::initializer_list. Now verify that it's
6518 // correct.
6519 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006520 if (Params->getMinRequiredArguments() != 1 ||
6521 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006522 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6523 return 0;
6524 }
6525
6526 return Template;
6527}
6528
6529QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6530 if (!StdInitializerList) {
6531 StdInitializerList = LookupStdInitializerList(*this, Loc);
6532 if (!StdInitializerList)
6533 return QualType();
6534 }
6535
6536 TemplateArgumentListInfo Args(Loc, Loc);
6537 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6538 Context.getTrivialTypeSourceInfo(Element,
6539 Loc)));
6540 return Context.getCanonicalType(
6541 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6542}
6543
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006544bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6545 // C++ [dcl.init.list]p2:
6546 // A constructor is an initializer-list constructor if its first parameter
6547 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6548 // std::initializer_list<E> for some type E, and either there are no other
6549 // parameters or else all other parameters have default arguments.
6550 if (Ctor->getNumParams() < 1 ||
6551 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6552 return false;
6553
6554 QualType ArgType = Ctor->getParamDecl(0)->getType();
6555 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6556 ArgType = RT->getPointeeType().getUnqualifiedType();
6557
6558 return isStdInitializerList(ArgType, 0);
6559}
6560
Douglas Gregora172e082011-03-26 22:25:30 +00006561/// \brief Determine whether a using statement is in a context where it will be
6562/// apply in all contexts.
6563static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6564 switch (CurContext->getDeclKind()) {
6565 case Decl::TranslationUnit:
6566 return true;
6567 case Decl::LinkageSpec:
6568 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6569 default:
6570 return false;
6571 }
6572}
6573
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006574namespace {
6575
6576// Callback to only accept typo corrections that are namespaces.
6577class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6578 public:
6579 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6580 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6581 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6582 }
6583 return false;
6584 }
6585};
6586
6587}
6588
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006589static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6590 CXXScopeSpec &SS,
6591 SourceLocation IdentLoc,
6592 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006593 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006594 R.clear();
6595 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006596 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006597 Validator)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006598 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6599 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006600 if (DeclContext *DC = S.computeDeclContext(SS, false))
6601 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6602 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie04ea41c2012-10-12 20:00:44 +00006603 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6604 CorrectedStr);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006605 else
6606 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6607 << Ident << CorrectedQuotedStr
6608 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006609
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006610 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6611 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006612
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006613 R.addDecl(Corrected.getCorrectionDecl());
6614 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006615 }
6616 return false;
6617}
6618
John McCall48871652010-08-21 09:40:31 +00006619Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006620 SourceLocation UsingLoc,
6621 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006622 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006623 SourceLocation IdentLoc,
6624 IdentifierInfo *NamespcName,
6625 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006626 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6627 assert(NamespcName && "Invalid NamespcName.");
6628 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006629
6630 // This can only happen along a recovery path.
6631 while (S->getFlags() & Scope::TemplateParamScope)
6632 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006633 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006634
Douglas Gregor889ceb72009-02-03 19:21:40 +00006635 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006636 NestedNameSpecifier *Qualifier = 0;
6637 if (SS.isSet())
6638 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6639
Douglas Gregor34074322009-01-14 22:20:51 +00006640 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006641 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6642 LookupParsedName(R, S, &SS);
6643 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006644 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006645
Douglas Gregorcdf87022010-06-29 17:53:46 +00006646 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006647 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006648 // Allow "using namespace std;" or "using namespace ::std;" even if
6649 // "std" hasn't been defined yet, for GCC compatibility.
6650 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6651 NamespcName->isStr("std")) {
6652 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006653 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006654 R.resolveKind();
6655 }
6656 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006657 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006658 }
6659
John McCall9f3059a2009-10-09 21:13:30 +00006660 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006661 NamedDecl *Named = R.getFoundDecl();
6662 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6663 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006664 // C++ [namespace.udir]p1:
6665 // A using-directive specifies that the names in the nominated
6666 // namespace can be used in the scope in which the
6667 // using-directive appears after the using-directive. During
6668 // unqualified name lookup (3.4.1), the names appear as if they
6669 // were declared in the nearest enclosing namespace which
6670 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006671 // namespace. [Note: in this context, "contains" means "contains
6672 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006673
6674 // Find enclosing context containing both using-directive and
6675 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006676 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006677 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6678 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6679 CommonAncestor = CommonAncestor->getParent();
6680
Sebastian Redla6602e92009-11-23 15:34:23 +00006681 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006682 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006683 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006684
Douglas Gregora172e082011-03-26 22:25:30 +00006685 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00006686 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006687 Diag(IdentLoc, diag::warn_using_directive_in_header);
6688 }
6689
Douglas Gregor889ceb72009-02-03 19:21:40 +00006690 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006691 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006692 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006693 }
6694
Richard Smith54ecd982013-02-20 19:22:51 +00006695 if (UDir)
6696 ProcessDeclAttributeList(S, UDir, AttrList);
6697
John McCall48871652010-08-21 09:40:31 +00006698 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006699}
6700
6701void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00006702 // If the scope has an associated entity and the using directive is at
6703 // namespace or translation unit scope, add the UsingDirectiveDecl into
6704 // its lookup structure so qualified name lookup can find it.
6705 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6706 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006707 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006708 else
Richard Smith05afe5e2012-03-13 03:12:56 +00006709 // Otherwise, it is at block sope. The using-directives will affect lookup
6710 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00006711 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006712}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006713
Douglas Gregorfec52632009-06-20 00:51:54 +00006714
John McCall48871652010-08-21 09:40:31 +00006715Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006716 AccessSpecifier AS,
6717 bool HasUsingKeyword,
6718 SourceLocation UsingLoc,
6719 CXXScopeSpec &SS,
6720 UnqualifiedId &Name,
6721 AttributeList *AttrList,
6722 bool IsTypeName,
6723 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006724 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006725
Douglas Gregor220f4272009-11-04 16:30:06 +00006726 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006727 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006728 case UnqualifiedId::IK_Identifier:
6729 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006730 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006731 case UnqualifiedId::IK_ConversionFunctionId:
6732 break;
6733
6734 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00006735 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00006736 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006737 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006738 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00006739 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00006740 diag::err_using_decl_constructor)
6741 << SS.getRange();
6742
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006743 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00006744
John McCall48871652010-08-21 09:40:31 +00006745 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006746
6747 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006748 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00006749 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006750 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006751
6752 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006753 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00006754 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006755 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006756 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006757
6758 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6759 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006760 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00006761 return 0;
John McCall3969e302009-12-08 07:46:18 +00006762
Richard Smithc2bc61b2013-03-18 21:12:30 +00006763 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00006764 // TODO: store that the declaration was written without 'using' and
6765 // talk about access decls instead of using decls in the
6766 // diagnostics.
6767 if (!HasUsingKeyword) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006768 UsingLoc = Name.getLocStart();
Richard Smithf026b602013-06-13 02:12:17 +00006769
6770 Diag(UsingLoc,
6771 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6772 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00006773 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00006774 }
6775
Douglas Gregorc4356532010-12-16 00:46:58 +00006776 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6777 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6778 return 0;
6779
John McCall3f746822009-11-17 05:59:44 +00006780 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006781 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006782 /* IsInstantiation */ false,
6783 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00006784 if (UD)
6785 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00006786
John McCall48871652010-08-21 09:40:31 +00006787 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00006788}
6789
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006790/// \brief Determine whether a using declaration considers the given
6791/// declarations as "equivalent", e.g., if they are redeclarations of
6792/// the same entity or are both typedefs of the same type.
6793static bool
6794IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6795 bool &SuppressRedeclaration) {
6796 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6797 SuppressRedeclaration = false;
6798 return true;
6799 }
6800
Richard Smithdda56e42011-04-15 14:24:37 +00006801 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6802 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006803 SuppressRedeclaration = true;
6804 return Context.hasSameType(TD1->getUnderlyingType(),
6805 TD2->getUnderlyingType());
6806 }
6807
6808 return false;
6809}
6810
6811
John McCall84d87672009-12-10 09:41:52 +00006812/// Determines whether to create a using shadow decl for a particular
6813/// decl, given the set of decls existing prior to this using lookup.
6814bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6815 const LookupResult &Previous) {
6816 // Diagnose finding a decl which is not from a base class of the
6817 // current class. We do this now because there are cases where this
6818 // function will silently decide not to build a shadow decl, which
6819 // will pre-empt further diagnostics.
6820 //
6821 // We don't need to do this in C++0x because we do the check once on
6822 // the qualifier.
6823 //
6824 // FIXME: diagnose the following if we care enough:
6825 // struct A { int foo; };
6826 // struct B : A { using A::foo; };
6827 // template <class T> struct C : A {};
6828 // template <class T> struct D : C<T> { using B::foo; } // <---
6829 // This is invalid (during instantiation) in C++03 because B::foo
6830 // resolves to the using decl in B, which is not a base class of D<T>.
6831 // We can't diagnose it immediately because C<T> is an unknown
6832 // specialization. The UsingShadowDecl in D<T> then points directly
6833 // to A::foo, which will look well-formed when we instantiate.
6834 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006835 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00006836 DeclContext *OrigDC = Orig->getDeclContext();
6837
6838 // Handle enums and anonymous structs.
6839 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6840 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6841 while (OrigRec->isAnonymousStructOrUnion())
6842 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6843
6844 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6845 if (OrigDC == CurContext) {
6846 Diag(Using->getLocation(),
6847 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006848 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006849 Diag(Orig->getLocation(), diag::note_using_decl_target);
6850 return true;
6851 }
6852
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006853 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00006854 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006855 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00006856 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006857 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006858 Diag(Orig->getLocation(), diag::note_using_decl_target);
6859 return true;
6860 }
6861 }
6862
6863 if (Previous.empty()) return false;
6864
6865 NamedDecl *Target = Orig;
6866 if (isa<UsingShadowDecl>(Target))
6867 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6868
John McCalla17e83e2009-12-11 02:33:26 +00006869 // If the target happens to be one of the previous declarations, we
6870 // don't have a conflict.
6871 //
6872 // FIXME: but we might be increasing its access, in which case we
6873 // should redeclare it.
6874 NamedDecl *NonTag = 0, *Tag = 0;
6875 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6876 I != E; ++I) {
6877 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006878 bool Result;
6879 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6880 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00006881
6882 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6883 }
6884
John McCall84d87672009-12-10 09:41:52 +00006885 if (Target->isFunctionOrFunctionTemplate()) {
6886 FunctionDecl *FD;
6887 if (isa<FunctionTemplateDecl>(Target))
6888 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6889 else
6890 FD = cast<FunctionDecl>(Target);
6891
6892 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00006893 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00006894 case Ovl_Overload:
6895 return false;
6896
6897 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00006898 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006899 break;
6900
6901 // We found a decl with the exact signature.
6902 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006903 // If we're in a record, we want to hide the target, so we
6904 // return true (without a diagnostic) to tell the caller not to
6905 // build a shadow decl.
6906 if (CurContext->isRecord())
6907 return true;
6908
6909 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00006910 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006911 break;
6912 }
6913
6914 Diag(Target->getLocation(), diag::note_using_decl_target);
6915 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6916 return true;
6917 }
6918
6919 // Target is not a function.
6920
John McCall84d87672009-12-10 09:41:52 +00006921 if (isa<TagDecl>(Target)) {
6922 // No conflict between a tag and a non-tag.
6923 if (!Tag) return false;
6924
John McCalle29c5cd2009-12-10 19:51:03 +00006925 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006926 Diag(Target->getLocation(), diag::note_using_decl_target);
6927 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6928 return true;
6929 }
6930
6931 // No conflict between a tag and a non-tag.
6932 if (!NonTag) return false;
6933
John McCalle29c5cd2009-12-10 19:51:03 +00006934 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006935 Diag(Target->getLocation(), diag::note_using_decl_target);
6936 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6937 return true;
6938}
6939
John McCall3f746822009-11-17 05:59:44 +00006940/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00006941UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00006942 UsingDecl *UD,
6943 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00006944
6945 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00006946 NamedDecl *Target = Orig;
6947 if (isa<UsingShadowDecl>(Target)) {
6948 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6949 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006950 }
6951
6952 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006953 = UsingShadowDecl::Create(Context, CurContext,
6954 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006955 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006956
6957 Shadow->setAccess(UD->getAccess());
6958 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6959 Shadow->setInvalidDecl();
6960
John McCall3f746822009-11-17 05:59:44 +00006961 if (S)
John McCall3969e302009-12-08 07:46:18 +00006962 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006963 else
John McCall3969e302009-12-08 07:46:18 +00006964 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006965
John McCall3969e302009-12-08 07:46:18 +00006966
John McCall84d87672009-12-10 09:41:52 +00006967 return Shadow;
6968}
John McCall3969e302009-12-08 07:46:18 +00006969
John McCall84d87672009-12-10 09:41:52 +00006970/// Hides a using shadow declaration. This is required by the current
6971/// using-decl implementation when a resolvable using declaration in a
6972/// class is followed by a declaration which would hide or override
6973/// one or more of the using decl's targets; for example:
6974///
6975/// struct Base { void foo(int); };
6976/// struct Derived : Base {
6977/// using Base::foo;
6978/// void foo(int);
6979/// };
6980///
6981/// The governing language is C++03 [namespace.udecl]p12:
6982///
6983/// When a using-declaration brings names from a base class into a
6984/// derived class scope, member functions in the derived class
6985/// override and/or hide member functions with the same name and
6986/// parameter types in a base class (rather than conflicting).
6987///
6988/// There are two ways to implement this:
6989/// (1) optimistically create shadow decls when they're not hidden
6990/// by existing declarations, or
6991/// (2) don't create any shadow decls (or at least don't make them
6992/// visible) until we've fully parsed/instantiated the class.
6993/// The problem with (1) is that we might have to retroactively remove
6994/// a shadow decl, which requires several O(n) operations because the
6995/// decl structures are (very reasonably) not designed for removal.
6996/// (2) avoids this but is very fiddly and phase-dependent.
6997void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006998 if (Shadow->getDeclName().getNameKind() ==
6999 DeclarationName::CXXConversionFunctionName)
7000 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7001
John McCall84d87672009-12-10 09:41:52 +00007002 // Remove it from the DeclContext...
7003 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007004
John McCall84d87672009-12-10 09:41:52 +00007005 // ...and the scope, if applicable...
7006 if (S) {
John McCall48871652010-08-21 09:40:31 +00007007 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007008 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007009 }
7010
John McCall84d87672009-12-10 09:41:52 +00007011 // ...and the using decl.
7012 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7013
7014 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007015 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007016}
7017
John McCalle61f2ba2009-11-18 02:36:19 +00007018/// Builds a using declaration.
7019///
7020/// \param IsInstantiation - Whether this call arises from an
7021/// instantiation of an unresolved using declaration. We treat
7022/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007023NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7024 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007025 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007026 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007027 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007028 bool IsInstantiation,
7029 bool IsTypeName,
7030 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007031 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007032 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007033 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007034
Anders Carlssonf038fc22009-08-28 05:49:21 +00007035 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007036
Anders Carlsson59140b32009-08-28 03:16:11 +00007037 if (SS.isEmpty()) {
7038 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007039 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007040 }
Mike Stump11289f42009-09-09 15:08:12 +00007041
John McCall84d87672009-12-10 09:41:52 +00007042 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007043 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007044 ForRedeclaration);
7045 Previous.setHideTags(false);
7046 if (S) {
7047 LookupName(Previous, S);
7048
7049 // It is really dumb that we have to do this.
7050 LookupResult::Filter F = Previous.makeFilter();
7051 while (F.hasNext()) {
7052 NamedDecl *D = F.next();
7053 if (!isDeclInScope(D, CurContext, S))
7054 F.erase();
7055 }
7056 F.done();
7057 } else {
7058 assert(IsInstantiation && "no scope in non-instantiation");
7059 assert(CurContext->isRecord() && "scope not record in instantiation");
7060 LookupQualifiedName(Previous, CurContext);
7061 }
7062
John McCall84d87672009-12-10 09:41:52 +00007063 // Check for invalid redeclarations.
7064 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7065 return 0;
7066
7067 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007068 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7069 return 0;
7070
John McCall84c16cf2009-11-12 03:15:40 +00007071 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007072 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007073 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007074 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00007075 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00007076 // FIXME: not all declaration name kinds are legal here
7077 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7078 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007079 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007080 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007081 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007082 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7083 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007084 }
John McCallb96ec562009-12-04 22:46:56 +00007085 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007086 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7087 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007088 }
John McCallb96ec562009-12-04 22:46:56 +00007089 D->setAccess(AS);
7090 CurContext->addDecl(D);
7091
7092 if (!LookupContext) return D;
7093 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007094
John McCall0b66eb32010-05-01 00:40:08 +00007095 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007096 UD->setInvalidDecl();
7097 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007098 }
7099
Richard Smith23d55872012-04-02 01:30:27 +00007100 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007101 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007102 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007103 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007104 return UD;
7105 }
7106
7107 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007108
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007109 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007110
John McCall3969e302009-12-08 07:46:18 +00007111 // Unlike most lookups, we don't always want to hide tag
7112 // declarations: tag names are visible through the using declaration
7113 // even if hidden by ordinary names, *except* in a dependent context
7114 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007115 if (!IsInstantiation)
7116 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007117
John McCall5dadb652012-04-07 03:04:20 +00007118 // For the purposes of this lookup, we have a base object type
7119 // equal to that of the current context.
7120 if (CurContext->isRecord()) {
7121 R.setBaseObjectType(
7122 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7123 }
7124
John McCall27b18f82009-11-17 02:14:36 +00007125 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007126
John McCall9f3059a2009-10-09 21:13:30 +00007127 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00007128 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007129 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007130 UD->setInvalidDecl();
7131 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007132 }
7133
John McCallb96ec562009-12-04 22:46:56 +00007134 if (R.isAmbiguous()) {
7135 UD->setInvalidDecl();
7136 return UD;
7137 }
Mike Stump11289f42009-09-09 15:08:12 +00007138
John McCalle61f2ba2009-11-18 02:36:19 +00007139 if (IsTypeName) {
7140 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007141 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007142 Diag(IdentLoc, diag::err_using_typename_non_type);
7143 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7144 Diag((*I)->getUnderlyingDecl()->getLocation(),
7145 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007146 UD->setInvalidDecl();
7147 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007148 }
7149 } else {
7150 // If we asked for a non-typename and we got a type, error out,
7151 // but only if this is an instantiation of an unresolved using
7152 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007153 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007154 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7155 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007156 UD->setInvalidDecl();
7157 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007158 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007159 }
7160
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007161 // C++0x N2914 [namespace.udecl]p6:
7162 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007163 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007164 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7165 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007166 UD->setInvalidDecl();
7167 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007168 }
Mike Stump11289f42009-09-09 15:08:12 +00007169
John McCall84d87672009-12-10 09:41:52 +00007170 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7171 if (!CheckUsingShadowDecl(UD, *I, Previous))
7172 BuildUsingShadowDecl(S, UD, *I);
7173 }
John McCall3f746822009-11-17 05:59:44 +00007174
7175 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007176}
7177
Sebastian Redl08905022011-02-05 19:23:19 +00007178/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007179bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7180 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007181
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007182 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007183 assert(SourceType &&
7184 "Using decl naming constructor doesn't have type in scope spec.");
7185 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7186
7187 // Check whether the named type is a direct base class.
7188 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7189 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7190 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7191 BaseIt != BaseE; ++BaseIt) {
7192 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7193 if (CanonicalSourceType == BaseType)
7194 break;
Richard Smith23d55872012-04-02 01:30:27 +00007195 if (BaseIt->getType()->isDependentType())
7196 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007197 }
7198
7199 if (BaseIt == BaseE) {
7200 // Did not find SourceType in the bases.
7201 Diag(UD->getUsingLocation(),
7202 diag::err_using_decl_constructor_not_in_direct_base)
7203 << UD->getNameInfo().getSourceRange()
7204 << QualType(SourceType, 0) << TargetClass;
7205 return true;
7206 }
7207
Richard Smith23d55872012-04-02 01:30:27 +00007208 if (!CurContext->isDependentContext())
7209 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007210
7211 return false;
7212}
7213
John McCall84d87672009-12-10 09:41:52 +00007214/// Checks that the given using declaration is not an invalid
7215/// redeclaration. Note that this is checking only for the using decl
7216/// itself, not for any ill-formedness among the UsingShadowDecls.
7217bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7218 bool isTypeName,
7219 const CXXScopeSpec &SS,
7220 SourceLocation NameLoc,
7221 const LookupResult &Prev) {
7222 // C++03 [namespace.udecl]p8:
7223 // C++0x [namespace.udecl]p10:
7224 // A using-declaration is a declaration and can therefore be used
7225 // repeatedly where (and only where) multiple declarations are
7226 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007227 //
John McCall032092f2010-11-29 18:01:58 +00007228 // That's in non-member contexts.
7229 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007230 return false;
7231
7232 NestedNameSpecifier *Qual
7233 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7234
7235 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7236 NamedDecl *D = *I;
7237
7238 bool DTypename;
7239 NestedNameSpecifier *DQual;
7240 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7241 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007242 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007243 } else if (UnresolvedUsingValueDecl *UD
7244 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7245 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007246 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007247 } else if (UnresolvedUsingTypenameDecl *UD
7248 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7249 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007250 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007251 } else continue;
7252
7253 // using decls differ if one says 'typename' and the other doesn't.
7254 // FIXME: non-dependent using decls?
7255 if (isTypeName != DTypename) continue;
7256
7257 // using decls differ if they name different scopes (but note that
7258 // template instantiation can cause this check to trigger when it
7259 // didn't before instantiation).
7260 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7261 Context.getCanonicalNestedNameSpecifier(DQual))
7262 continue;
7263
7264 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007265 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007266 return true;
7267 }
7268
7269 return false;
7270}
7271
John McCall3969e302009-12-08 07:46:18 +00007272
John McCallb96ec562009-12-04 22:46:56 +00007273/// Checks that the given nested-name qualifier used in a using decl
7274/// in the current context is appropriately related to the current
7275/// scope. If an error is found, diagnoses it and returns true.
7276bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7277 const CXXScopeSpec &SS,
7278 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007279 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007280
John McCall3969e302009-12-08 07:46:18 +00007281 if (!CurContext->isRecord()) {
7282 // C++03 [namespace.udecl]p3:
7283 // C++0x [namespace.udecl]p8:
7284 // A using-declaration for a class member shall be a member-declaration.
7285
7286 // If we weren't able to compute a valid scope, it must be a
7287 // dependent class scope.
7288 if (!NamedContext || NamedContext->isRecord()) {
7289 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7290 << SS.getRange();
7291 return true;
7292 }
7293
7294 // Otherwise, everything is known to be fine.
7295 return false;
7296 }
7297
7298 // The current scope is a record.
7299
7300 // If the named context is dependent, we can't decide much.
7301 if (!NamedContext) {
7302 // FIXME: in C++0x, we can diagnose if we can prove that the
7303 // nested-name-specifier does not refer to a base class, which is
7304 // still possible in some cases.
7305
7306 // Otherwise we have to conservatively report that things might be
7307 // okay.
7308 return false;
7309 }
7310
7311 if (!NamedContext->isRecord()) {
7312 // Ideally this would point at the last name in the specifier,
7313 // but we don't have that level of source info.
7314 Diag(SS.getRange().getBegin(),
7315 diag::err_using_decl_nested_name_specifier_is_not_class)
7316 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7317 return true;
7318 }
7319
Douglas Gregor7c842292010-12-21 07:41:49 +00007320 if (!NamedContext->isDependentContext() &&
7321 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7322 return true;
7323
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007324 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007325 // C++0x [namespace.udecl]p3:
7326 // In a using-declaration used as a member-declaration, the
7327 // nested-name-specifier shall name a base class of the class
7328 // being defined.
7329
7330 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7331 cast<CXXRecordDecl>(NamedContext))) {
7332 if (CurContext == NamedContext) {
7333 Diag(NameLoc,
7334 diag::err_using_decl_nested_name_specifier_is_current_class)
7335 << SS.getRange();
7336 return true;
7337 }
7338
7339 Diag(SS.getRange().getBegin(),
7340 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7341 << (NestedNameSpecifier*) SS.getScopeRep()
7342 << cast<CXXRecordDecl>(CurContext)
7343 << SS.getRange();
7344 return true;
7345 }
7346
7347 return false;
7348 }
7349
7350 // C++03 [namespace.udecl]p4:
7351 // A using-declaration used as a member-declaration shall refer
7352 // to a member of a base class of the class being defined [etc.].
7353
7354 // Salient point: SS doesn't have to name a base class as long as
7355 // lookup only finds members from base classes. Therefore we can
7356 // diagnose here only if we can prove that that can't happen,
7357 // i.e. if the class hierarchies provably don't intersect.
7358
7359 // TODO: it would be nice if "definitely valid" results were cached
7360 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7361 // need to be repeated.
7362
7363 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007364 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007365
7366 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7367 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7368 Data->Bases.insert(Base);
7369 return true;
7370 }
7371
7372 bool hasDependentBases(const CXXRecordDecl *Class) {
7373 return !Class->forallBases(collect, this);
7374 }
7375
7376 /// Returns true if the base is dependent or is one of the
7377 /// accumulated base classes.
7378 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7379 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7380 return !Data->Bases.count(Base);
7381 }
7382
7383 bool mightShareBases(const CXXRecordDecl *Class) {
7384 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7385 }
7386 };
7387
7388 UserData Data;
7389
7390 // Returns false if we find a dependent base.
7391 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7392 return false;
7393
7394 // Returns false if the class has a dependent base or if it or one
7395 // of its bases is present in the base set of the current context.
7396 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7397 return false;
7398
7399 Diag(SS.getRange().getBegin(),
7400 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7401 << (NestedNameSpecifier*) SS.getScopeRep()
7402 << cast<CXXRecordDecl>(CurContext)
7403 << SS.getRange();
7404
7405 return true;
John McCallb96ec562009-12-04 22:46:56 +00007406}
7407
Richard Smithdda56e42011-04-15 14:24:37 +00007408Decl *Sema::ActOnAliasDeclaration(Scope *S,
7409 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007410 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007411 SourceLocation UsingLoc,
7412 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007413 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007414 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007415 // Skip up to the relevant declaration scope.
7416 while (S->getFlags() & Scope::TemplateParamScope)
7417 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007418 assert((S->getFlags() & Scope::DeclScope) &&
7419 "got alias-declaration outside of declaration scope");
7420
7421 if (Type.isInvalid())
7422 return 0;
7423
7424 bool Invalid = false;
7425 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7426 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007427 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007428
7429 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7430 return 0;
7431
7432 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007433 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007434 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007435 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7436 TInfo->getTypeLoc().getBeginLoc());
7437 }
Richard Smithdda56e42011-04-15 14:24:37 +00007438
7439 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7440 LookupName(Previous, S);
7441
7442 // Warn about shadowing the name of a template parameter.
7443 if (Previous.isSingleResult() &&
7444 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007445 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007446 Previous.clear();
7447 }
7448
7449 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7450 "name in alias declaration must be an identifier");
7451 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7452 Name.StartLocation,
7453 Name.Identifier, TInfo);
7454
7455 NewTD->setAccess(AS);
7456
7457 if (Invalid)
7458 NewTD->setInvalidDecl();
7459
Richard Smith54ecd982013-02-20 19:22:51 +00007460 ProcessDeclAttributeList(S, NewTD, AttrList);
7461
Richard Smith3f1b5d02011-05-05 21:57:07 +00007462 CheckTypedefForVariablyModifiedType(S, NewTD);
7463 Invalid |= NewTD->isInvalidDecl();
7464
Richard Smithdda56e42011-04-15 14:24:37 +00007465 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007466
7467 NamedDecl *NewND;
7468 if (TemplateParamLists.size()) {
7469 TypeAliasTemplateDecl *OldDecl = 0;
7470 TemplateParameterList *OldTemplateParams = 0;
7471
7472 if (TemplateParamLists.size() != 1) {
7473 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007474 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7475 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007476 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007477 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007478
7479 // Only consider previous declarations in the same scope.
7480 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7481 /*ExplicitInstantiationOrSpecialization*/false);
7482 if (!Previous.empty()) {
7483 Redeclaration = true;
7484
7485 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7486 if (!OldDecl && !Invalid) {
7487 Diag(UsingLoc, diag::err_redefinition_different_kind)
7488 << Name.Identifier;
7489
7490 NamedDecl *OldD = Previous.getRepresentativeDecl();
7491 if (OldD->getLocation().isValid())
7492 Diag(OldD->getLocation(), diag::note_previous_definition);
7493
7494 Invalid = true;
7495 }
7496
7497 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7498 if (TemplateParameterListsAreEqual(TemplateParams,
7499 OldDecl->getTemplateParameters(),
7500 /*Complain=*/true,
7501 TPL_TemplateMatch))
7502 OldTemplateParams = OldDecl->getTemplateParameters();
7503 else
7504 Invalid = true;
7505
7506 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7507 if (!Invalid &&
7508 !Context.hasSameType(OldTD->getUnderlyingType(),
7509 NewTD->getUnderlyingType())) {
7510 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7511 // but we can't reasonably accept it.
7512 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7513 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7514 if (OldTD->getLocation().isValid())
7515 Diag(OldTD->getLocation(), diag::note_previous_definition);
7516 Invalid = true;
7517 }
7518 }
7519 }
7520
7521 // Merge any previous default template arguments into our parameters,
7522 // and check the parameter list.
7523 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7524 TPC_TypeAliasTemplate))
7525 return 0;
7526
7527 TypeAliasTemplateDecl *NewDecl =
7528 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7529 Name.Identifier, TemplateParams,
7530 NewTD);
7531
7532 NewDecl->setAccess(AS);
7533
7534 if (Invalid)
7535 NewDecl->setInvalidDecl();
7536 else if (OldDecl)
7537 NewDecl->setPreviousDeclaration(OldDecl);
7538
7539 NewND = NewDecl;
7540 } else {
7541 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7542 NewND = NewTD;
7543 }
Richard Smithdda56e42011-04-15 14:24:37 +00007544
7545 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007546 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007547
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007548 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007549 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007550}
7551
John McCall48871652010-08-21 09:40:31 +00007552Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007553 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007554 SourceLocation AliasLoc,
7555 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007556 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007557 SourceLocation IdentLoc,
7558 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007559
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007560 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007561 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7562 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007563
Anders Carlssondca83c42009-03-28 06:23:46 +00007564 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007565 NamedDecl *PrevDecl
7566 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7567 ForRedeclaration);
7568 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7569 PrevDecl = 0;
7570
7571 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007572 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007573 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007574 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007575 // FIXME: At some point, we'll want to create the (redundant)
7576 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007577 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007578 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007579 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007580 }
Mike Stump11289f42009-09-09 15:08:12 +00007581
Anders Carlssondca83c42009-03-28 06:23:46 +00007582 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7583 diag::err_redefinition_different_kind;
7584 Diag(AliasLoc, DiagID) << Alias;
7585 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007586 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007587 }
7588
John McCall27b18f82009-11-17 02:14:36 +00007589 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007590 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007591
John McCall9f3059a2009-10-09 21:13:30 +00007592 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007593 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007594 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007595 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007596 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007597 }
Mike Stump11289f42009-09-09 15:08:12 +00007598
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007599 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00007600 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00007601 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00007602 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007603
John McCalld8d0d432010-02-16 06:53:13 +00007604 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00007605 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00007606}
7607
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007608Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00007609Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7610 CXXMethodDecl *MD) {
7611 CXXRecordDecl *ClassDecl = MD->getParent();
7612
Douglas Gregor6d880b12010-07-01 22:31:05 +00007613 // C++ [except.spec]p14:
7614 // An implicitly declared special member function (Clause 12) shall have an
7615 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00007616 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007617 if (ClassDecl->isInvalidDecl())
7618 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00007619
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007620 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007621 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7622 BEnd = ClassDecl->bases_end();
7623 B != BEnd; ++B) {
7624 if (B->isVirtual()) // Handled below.
7625 continue;
7626
Douglas Gregor9672f922010-07-03 00:47:00 +00007627 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7628 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007629 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7630 // If this is a deleted function, add it anyway. This might be conformant
7631 // with the standard. This might not. I'm not sure. It might not matter.
7632 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007633 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007634 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007635 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007636
7637 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007638 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7639 BEnd = ClassDecl->vbases_end();
7640 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007641 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7642 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007643 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7644 // If this is a deleted function, add it anyway. This might be conformant
7645 // with the standard. This might not. I'm not sure. It might not matter.
7646 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007647 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007648 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007649 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007650
7651 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007652 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7653 FEnd = ClassDecl->field_end();
7654 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00007655 if (F->hasInClassInitializer()) {
7656 if (Expr *E = F->getInClassInitializer())
7657 ExceptSpec.CalledExpr(E);
7658 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00007659 // DR1351:
7660 // If the brace-or-equal-initializer of a non-static data member
7661 // invokes a defaulted default constructor of its class or of an
7662 // enclosing class in a potentially evaluated subexpression, the
7663 // program is ill-formed.
7664 //
7665 // This resolution is unworkable: the exception specification of the
7666 // default constructor can be needed in an unevaluated context, in
7667 // particular, in the operand of a noexcept-expression, and we can be
7668 // unable to compute an exception specification for an enclosed class.
7669 //
7670 // We do not allow an in-class initializer to require the evaluation
7671 // of the exception specification for any in-class initializer whose
7672 // definition is not lexically complete.
7673 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00007674 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00007675 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00007676 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7677 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7678 // If this is a deleted function, add it anyway. This might be conformant
7679 // with the standard. This might not. I'm not sure. It might not matter.
7680 // In particular, the problem is that this function never gets called. It
7681 // might just be ill-formed because this function attempts to refer to
7682 // a deleted function here.
7683 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007684 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007685 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007686 }
John McCalldb40c7f2010-12-14 08:05:40 +00007687
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007688 return ExceptSpec;
7689}
7690
Richard Smithc2bc61b2013-03-18 21:12:30 +00007691Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00007692Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7693 CXXRecordDecl *ClassDecl = CD->getParent();
7694
7695 // C++ [except.spec]p14:
7696 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00007697 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00007698 if (ClassDecl->isInvalidDecl())
7699 return ExceptSpec;
7700
7701 // Inherited constructor.
7702 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7703 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7704 // FIXME: Copying or moving the parameters could add extra exceptions to the
7705 // set, as could the default arguments for the inherited constructor. This
7706 // will be addressed when we implement the resolution of core issue 1351.
7707 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7708
7709 // Direct base-class constructors.
7710 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7711 BEnd = ClassDecl->bases_end();
7712 B != BEnd; ++B) {
7713 if (B->isVirtual()) // Handled below.
7714 continue;
7715
7716 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7717 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7718 if (BaseClassDecl == InheritedDecl)
7719 continue;
7720 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7721 if (Constructor)
7722 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7723 }
7724 }
7725
7726 // Virtual base-class constructors.
7727 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7728 BEnd = ClassDecl->vbases_end();
7729 B != BEnd; ++B) {
7730 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7731 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7732 if (BaseClassDecl == InheritedDecl)
7733 continue;
7734 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7735 if (Constructor)
7736 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7737 }
7738 }
7739
7740 // Field constructors.
7741 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7742 FEnd = ClassDecl->field_end();
7743 F != FEnd; ++F) {
7744 if (F->hasInClassInitializer()) {
7745 if (Expr *E = F->getInClassInitializer())
7746 ExceptSpec.CalledExpr(E);
7747 else if (!F->isInvalidDecl())
7748 Diag(CD->getLocation(),
7749 diag::err_in_class_initializer_references_def_ctor) << CD;
7750 } else if (const RecordType *RecordTy
7751 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7752 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7753 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7754 if (Constructor)
7755 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7756 }
7757 }
7758
Richard Smithc2bc61b2013-03-18 21:12:30 +00007759 return ExceptSpec;
7760}
7761
Richard Smith8bf22e52012-11-29 01:34:07 +00007762namespace {
7763/// RAII object to register a special member as being currently declared.
7764struct DeclaringSpecialMember {
7765 Sema &S;
7766 Sema::SpecialMemberDecl D;
7767 bool WasAlreadyBeingDeclared;
7768
7769 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7770 : S(S), D(RD, CSM) {
7771 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7772 if (WasAlreadyBeingDeclared)
7773 // This almost never happens, but if it does, ensure that our cache
7774 // doesn't contain a stale result.
7775 S.SpecialMemberCache.clear();
7776
7777 // FIXME: Register a note to be produced if we encounter an error while
7778 // declaring the special member.
7779 }
7780 ~DeclaringSpecialMember() {
7781 if (!WasAlreadyBeingDeclared)
7782 S.SpecialMembersBeingDeclared.erase(D);
7783 }
7784
7785 /// \brief Are we already trying to declare this special member?
7786 bool isAlreadyBeingDeclared() const {
7787 return WasAlreadyBeingDeclared;
7788 }
7789};
7790}
7791
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007792CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7793 CXXRecordDecl *ClassDecl) {
7794 // C++ [class.ctor]p5:
7795 // A default constructor for a class X is a constructor of class X
7796 // that can be called without an argument. If there is no
7797 // user-declared constructor for class X, a default constructor is
7798 // implicitly declared. An implicitly-declared default constructor
7799 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00007800 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007801 "Should not build implicit default constructor!");
7802
Richard Smith8bf22e52012-11-29 01:34:07 +00007803 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7804 if (DSM.isAlreadyBeingDeclared())
7805 return 0;
7806
Richard Smithb5800092012-06-10 05:43:50 +00007807 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7808 CXXDefaultConstructor,
7809 false);
7810
Douglas Gregor6d880b12010-07-01 22:31:05 +00007811 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007812 CanQualType ClassType
7813 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007814 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007815 DeclarationName Name
7816 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007817 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00007818 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00007819 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00007820 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00007821 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007822 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00007823 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007824 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00007825
7826 // Build an exception specification pointing back at this constructor.
7827 FunctionProtoType::ExtProtoInfo EPI;
7828 EPI.ExceptionSpecType = EST_Unevaluated;
7829 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007830 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00007831
Richard Smith6b02d462012-12-08 08:32:28 +00007832 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7833 // constructors is easy to compute.
7834 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7835
7836 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00007837 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00007838
Douglas Gregor9672f922010-07-03 00:47:00 +00007839 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00007840 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00007841
Douglas Gregor0be31a22010-07-02 17:43:08 +00007842 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00007843 PushOnScopeChains(DefaultCon, S, false);
7844 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007845
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007846 return DefaultCon;
7847}
7848
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007849void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7850 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00007851 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007852 !Constructor->doesThisDeclarationHaveABody() &&
7853 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007854 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007855
Anders Carlsson423f5d82010-04-23 16:04:08 +00007856 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00007857 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00007858
Eli Friedmaneaf34142012-10-18 20:14:08 +00007859 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007860 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00007861 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007862 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007863 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007864 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00007865 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00007866 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00007867 }
Douglas Gregor73193272010-09-20 16:48:21 +00007868
7869 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00007870 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00007871
7872 Constructor->setUsed();
7873 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007874
7875 if (ASTMutationListener *L = getASTMutationListener()) {
7876 L->CompletedImplicitDefinition(Constructor);
7877 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007878}
7879
Richard Smith938f40b2011-06-11 17:19:42 +00007880void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smithbd305122012-12-11 01:14:52 +00007881 // Check that any explicitly-defaulted methods have exception specifications
7882 // compatible with their implicit exception specifications.
7883 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00007884}
7885
Richard Smith185be182013-04-10 05:48:59 +00007886namespace {
7887/// Information on inheriting constructors to declare.
7888class InheritingConstructorInfo {
7889public:
7890 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7891 : SemaRef(SemaRef), Derived(Derived) {
7892 // Mark the constructors that we already have in the derived class.
7893 //
7894 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7895 // unless there is a user-declared constructor with the same signature in
7896 // the class where the using-declaration appears.
7897 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7898 }
7899
7900 void inheritAll(CXXRecordDecl *RD) {
7901 visitAll(RD, &InheritingConstructorInfo::inherit);
7902 }
7903
7904private:
7905 /// Information about an inheriting constructor.
7906 struct InheritingConstructor {
7907 InheritingConstructor()
7908 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7909
7910 /// If \c true, a constructor with this signature is already declared
7911 /// in the derived class.
7912 bool DeclaredInDerived;
7913
7914 /// The constructor which is inherited.
7915 const CXXConstructorDecl *BaseCtor;
7916
7917 /// The derived constructor we declared.
7918 CXXConstructorDecl *DerivedCtor;
7919 };
7920
7921 /// Inheriting constructors with a given canonical type. There can be at
7922 /// most one such non-template constructor, and any number of templated
7923 /// constructors.
7924 struct InheritingConstructorsForType {
7925 InheritingConstructor NonTemplate;
7926 llvm::SmallVector<
7927 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7928
7929 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7930 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7931 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7932 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7933 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7934 false, S.TPL_TemplateMatch))
7935 return Templates[I].second;
7936 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7937 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00007938 }
Richard Smith185be182013-04-10 05:48:59 +00007939
7940 return NonTemplate;
7941 }
7942 };
7943
7944 /// Get or create the inheriting constructor record for a constructor.
7945 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7946 QualType CtorType) {
7947 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7948 .getEntry(SemaRef, Ctor);
7949 }
7950
7951 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7952
7953 /// Process all constructors for a class.
7954 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7955 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7956 CtorE = RD->ctor_end();
7957 CtorIt != CtorE; ++CtorIt)
7958 (this->*Callback)(*CtorIt);
7959 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7960 I(RD->decls_begin()), E(RD->decls_end());
7961 I != E; ++I) {
7962 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7963 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7964 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00007965 }
7966 }
Richard Smith185be182013-04-10 05:48:59 +00007967
7968 /// Note that a constructor (or constructor template) was declared in Derived.
7969 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7970 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7971 }
7972
7973 /// Inherit a single constructor.
7974 void inherit(const CXXConstructorDecl *Ctor) {
7975 const FunctionProtoType *CtorType =
7976 Ctor->getType()->castAs<FunctionProtoType>();
7977 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7978 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7979
7980 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7981
7982 // Core issue (no number yet): the ellipsis is always discarded.
7983 if (EPI.Variadic) {
7984 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7985 SemaRef.Diag(Ctor->getLocation(),
7986 diag::note_using_decl_constructor_ellipsis);
7987 EPI.Variadic = false;
7988 }
7989
7990 // Declare a constructor for each number of parameters.
7991 //
7992 // C++11 [class.inhctor]p1:
7993 // The candidate set of inherited constructors from the class X named in
7994 // the using-declaration consists of [... modulo defects ...] for each
7995 // constructor or constructor template of X, the set of constructors or
7996 // constructor templates that results from omitting any ellipsis parameter
7997 // specification and successively omitting parameters with a default
7998 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00007999 unsigned MinParams = minParamsToInherit(Ctor);
8000 unsigned Params = Ctor->getNumParams();
8001 if (Params >= MinParams) {
8002 do
8003 declareCtor(UsingLoc, Ctor,
8004 SemaRef.Context.getFunctionType(
8005 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8006 while (Params > MinParams &&
8007 Ctor->getParamDecl(--Params)->hasDefaultArg());
8008 }
Richard Smith185be182013-04-10 05:48:59 +00008009 }
8010
8011 /// Find the using-declaration which specified that we should inherit the
8012 /// constructors of \p Base.
8013 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8014 // No fancy lookup required; just look for the base constructor name
8015 // directly within the derived class.
8016 ASTContext &Context = SemaRef.Context;
8017 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8018 Context.getCanonicalType(Context.getRecordType(Base)));
8019 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8020 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8021 }
8022
8023 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8024 // C++11 [class.inhctor]p3:
8025 // [F]or each constructor template in the candidate set of inherited
8026 // constructors, a constructor template is implicitly declared
8027 if (Ctor->getDescribedFunctionTemplate())
8028 return 0;
8029
8030 // For each non-template constructor in the candidate set of inherited
8031 // constructors other than a constructor having no parameters or a
8032 // copy/move constructor having a single parameter, a constructor is
8033 // implicitly declared [...]
8034 if (Ctor->getNumParams() == 0)
8035 return 1;
8036 if (Ctor->isCopyOrMoveConstructor())
8037 return 2;
8038
8039 // Per discussion on core reflector, never inherit a constructor which
8040 // would become a default, copy, or move constructor of Derived either.
8041 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8042 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8043 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8044 }
8045
8046 /// Declare a single inheriting constructor, inheriting the specified
8047 /// constructor, with the given type.
8048 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8049 QualType DerivedType) {
8050 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8051
8052 // C++11 [class.inhctor]p3:
8053 // ... a constructor is implicitly declared with the same constructor
8054 // characteristics unless there is a user-declared constructor with
8055 // the same signature in the class where the using-declaration appears
8056 if (Entry.DeclaredInDerived)
8057 return;
8058
8059 // C++11 [class.inhctor]p7:
8060 // If two using-declarations declare inheriting constructors with the
8061 // same signature, the program is ill-formed
8062 if (Entry.DerivedCtor) {
8063 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8064 // Only diagnose this once per constructor.
8065 if (Entry.DerivedCtor->isInvalidDecl())
8066 return;
8067 Entry.DerivedCtor->setInvalidDecl();
8068
8069 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8070 SemaRef.Diag(BaseCtor->getLocation(),
8071 diag::note_using_decl_constructor_conflict_current_ctor);
8072 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8073 diag::note_using_decl_constructor_conflict_previous_ctor);
8074 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8075 diag::note_using_decl_constructor_conflict_previous_using);
8076 } else {
8077 // Core issue (no number): if the same inheriting constructor is
8078 // produced by multiple base class constructors from the same base
8079 // class, the inheriting constructor is defined as deleted.
8080 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8081 }
8082
8083 return;
8084 }
8085
8086 ASTContext &Context = SemaRef.Context;
8087 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8088 Context.getCanonicalType(Context.getRecordType(Derived)));
8089 DeclarationNameInfo NameInfo(Name, UsingLoc);
8090
8091 TemplateParameterList *TemplateParams = 0;
8092 if (const FunctionTemplateDecl *FTD =
8093 BaseCtor->getDescribedFunctionTemplate()) {
8094 TemplateParams = FTD->getTemplateParameters();
8095 // We're reusing template parameters from a different DeclContext. This
8096 // is questionable at best, but works out because the template depth in
8097 // both places is guaranteed to be 0.
8098 // FIXME: Rebuild the template parameters in the new context, and
8099 // transform the function type to refer to them.
8100 }
8101
8102 // Build type source info pointing at the using-declaration. This is
8103 // required by template instantiation.
8104 TypeSourceInfo *TInfo =
8105 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8106 FunctionProtoTypeLoc ProtoLoc =
8107 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8108
8109 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8110 Context, Derived, UsingLoc, NameInfo, DerivedType,
8111 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8112 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8113
8114 // Build an unevaluated exception specification for this constructor.
8115 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8116 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8117 EPI.ExceptionSpecType = EST_Unevaluated;
8118 EPI.ExceptionSpecDecl = DerivedCtor;
8119 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8120 FPT->getArgTypes(), EPI));
8121
8122 // Build the parameter declarations.
8123 SmallVector<ParmVarDecl *, 16> ParamDecls;
8124 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8125 TypeSourceInfo *TInfo =
8126 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8127 ParmVarDecl *PD = ParmVarDecl::Create(
8128 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8129 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8130 PD->setScopeInfo(0, I);
8131 PD->setImplicit();
8132 ParamDecls.push_back(PD);
8133 ProtoLoc.setArg(I, PD);
8134 }
8135
8136 // Set up the new constructor.
8137 DerivedCtor->setAccess(BaseCtor->getAccess());
8138 DerivedCtor->setParams(ParamDecls);
8139 DerivedCtor->setInheritedConstructor(BaseCtor);
8140 if (BaseCtor->isDeleted())
8141 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8142
8143 // If this is a constructor template, build the template declaration.
8144 if (TemplateParams) {
8145 FunctionTemplateDecl *DerivedTemplate =
8146 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8147 TemplateParams, DerivedCtor);
8148 DerivedTemplate->setAccess(BaseCtor->getAccess());
8149 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8150 Derived->addDecl(DerivedTemplate);
8151 } else {
8152 Derived->addDecl(DerivedCtor);
8153 }
8154
8155 Entry.BaseCtor = BaseCtor;
8156 Entry.DerivedCtor = DerivedCtor;
8157 }
8158
8159 Sema &SemaRef;
8160 CXXRecordDecl *Derived;
8161 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8162 MapType Map;
8163};
8164}
8165
8166void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8167 // Defer declaring the inheriting constructors until the class is
8168 // instantiated.
8169 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008170 return;
8171
Richard Smith185be182013-04-10 05:48:59 +00008172 // Find base classes from which we might inherit constructors.
8173 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8174 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8175 BaseE = ClassDecl->bases_end();
8176 BaseIt != BaseE; ++BaseIt)
8177 if (BaseIt->getInheritConstructors())
8178 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008179
Richard Smith185be182013-04-10 05:48:59 +00008180 // Go no further if we're not inheriting any constructors.
8181 if (InheritedBases.empty())
8182 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008183
Richard Smith185be182013-04-10 05:48:59 +00008184 // Declare the inherited constructors.
8185 InheritingConstructorInfo ICI(*this, ClassDecl);
8186 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8187 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008188}
8189
Richard Smithc2bc61b2013-03-18 21:12:30 +00008190void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8191 CXXConstructorDecl *Constructor) {
8192 CXXRecordDecl *ClassDecl = Constructor->getParent();
8193 assert(Constructor->getInheritedConstructor() &&
8194 !Constructor->doesThisDeclarationHaveABody() &&
8195 !Constructor->isDeleted());
8196
8197 SynthesizedFunctionScope Scope(*this, Constructor);
8198 DiagnosticErrorTrap Trap(Diags);
8199 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8200 Trap.hasErrorOccurred()) {
8201 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8202 << Context.getTagDeclType(ClassDecl);
8203 Constructor->setInvalidDecl();
8204 return;
8205 }
8206
8207 SourceLocation Loc = Constructor->getLocation();
8208 Constructor->setBody(new (Context) CompoundStmt(Loc));
8209
8210 Constructor->setUsed();
8211 MarkVTableUsed(CurrentLocation, ClassDecl);
8212
8213 if (ASTMutationListener *L = getASTMutationListener()) {
8214 L->CompletedImplicitDefinition(Constructor);
8215 }
8216}
8217
8218
Alexis Huntf91729462011-05-12 22:46:25 +00008219Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008220Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8221 CXXRecordDecl *ClassDecl = MD->getParent();
8222
Douglas Gregorf1203042010-07-01 19:09:28 +00008223 // C++ [except.spec]p14:
8224 // An implicitly declared special member function (Clause 12) shall have
8225 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008226 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008227 if (ClassDecl->isInvalidDecl())
8228 return ExceptSpec;
8229
Douglas Gregorf1203042010-07-01 19:09:28 +00008230 // Direct base-class destructors.
8231 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8232 BEnd = ClassDecl->bases_end();
8233 B != BEnd; ++B) {
8234 if (B->isVirtual()) // Handled below.
8235 continue;
8236
8237 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008238 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008239 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008240 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008241
Douglas Gregorf1203042010-07-01 19:09:28 +00008242 // Virtual base-class destructors.
8243 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8244 BEnd = ClassDecl->vbases_end();
8245 B != BEnd; ++B) {
8246 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008247 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008248 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008249 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008250
Douglas Gregorf1203042010-07-01 19:09:28 +00008251 // Field destructors.
8252 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8253 FEnd = ClassDecl->field_end();
8254 F != FEnd; ++F) {
8255 if (const RecordType *RecordTy
8256 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008257 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008258 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008259 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008260
Alexis Huntf91729462011-05-12 22:46:25 +00008261 return ExceptSpec;
8262}
8263
8264CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8265 // C++ [class.dtor]p2:
8266 // If a class has no user-declared destructor, a destructor is
8267 // declared implicitly. An implicitly-declared destructor is an
8268 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008269 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008270
Richard Smith8bf22e52012-11-29 01:34:07 +00008271 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8272 if (DSM.isAlreadyBeingDeclared())
8273 return 0;
8274
Douglas Gregor7454c562010-07-02 20:37:36 +00008275 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008276 CanQualType ClassType
8277 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008278 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008279 DeclarationName Name
8280 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008281 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008282 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008283 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8284 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008285 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008286 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008287 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008288 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008289
8290 // Build an exception specification pointing back at this destructor.
8291 FunctionProtoType::ExtProtoInfo EPI;
8292 EPI.ExceptionSpecType = EST_Unevaluated;
8293 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008294 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008295
Richard Smith6b02d462012-12-08 08:32:28 +00008296 AddOverriddenMethods(ClassDecl, Destructor);
8297
8298 // We don't need to use SpecialMemberIsTrivial here; triviality for
8299 // destructors is easy to compute.
8300 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8301
8302 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008303 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008304
Douglas Gregor7454c562010-07-02 20:37:36 +00008305 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008306 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008307
Douglas Gregor7454c562010-07-02 20:37:36 +00008308 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008309 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008310 PushOnScopeChains(Destructor, S, false);
8311 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008312
Douglas Gregorf1203042010-07-01 19:09:28 +00008313 return Destructor;
8314}
8315
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008316void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008317 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008318 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008319 !Destructor->doesThisDeclarationHaveABody() &&
8320 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008321 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008322 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008323 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008324
Douglas Gregor54818f02010-05-12 16:39:35 +00008325 if (Destructor->isInvalidDecl())
8326 return;
8327
Eli Friedmaneaf34142012-10-18 20:14:08 +00008328 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008329
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008330 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008331 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8332 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008333
Douglas Gregor54818f02010-05-12 16:39:35 +00008334 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008335 Diag(CurrentLocation, diag::note_member_synthesized_at)
8336 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8337
8338 Destructor->setInvalidDecl();
8339 return;
8340 }
8341
Douglas Gregor73193272010-09-20 16:48:21 +00008342 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008343 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008344 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008345 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00008346 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008347
8348 if (ASTMutationListener *L = getASTMutationListener()) {
8349 L->CompletedImplicitDefinition(Destructor);
8350 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008351}
8352
Richard Smith84973e52012-04-21 18:42:51 +00008353/// \brief Perform any semantic analysis which needs to be delayed until all
8354/// pending class member declarations have been parsed.
8355void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008356 // If the context is an invalid C++ class, just suppress these checks.
8357 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8358 if (Record->isInvalidDecl()) {
8359 DelayedDestructorExceptionSpecChecks.clear();
8360 return;
8361 }
8362 }
8363
Richard Smith84973e52012-04-21 18:42:51 +00008364 // Perform any deferred checking of exception specifications for virtual
8365 // destructors.
8366 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8367 i != e; ++i) {
8368 const CXXDestructorDecl *Dtor =
8369 DelayedDestructorExceptionSpecChecks[i].first;
8370 assert(!Dtor->getParent()->isDependentType() &&
8371 "Should not ever add destructors of templates into the list.");
8372 CheckOverridingFunctionExceptionSpec(Dtor,
8373 DelayedDestructorExceptionSpecChecks[i].second);
8374 }
8375 DelayedDestructorExceptionSpecChecks.clear();
8376}
8377
Richard Smithd3b5c9082012-07-27 04:22:15 +00008378void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8379 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008380 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008381 "adjusting dtor exception specs was introduced in c++11");
8382
Sebastian Redl623ea822011-05-19 05:13:44 +00008383 // C++11 [class.dtor]p3:
8384 // A declaration of a destructor that does not have an exception-
8385 // specification is implicitly considered to have the same exception-
8386 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008387 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008388 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008389 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008390 return;
8391
Chandler Carruth9a797572011-09-20 04:55:26 +00008392 // Replace the destructor's type, building off the existing one. Fortunately,
8393 // the only thing of interest in the destructor type is its extended info.
8394 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008395 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8396 EPI.ExceptionSpecType = EST_Unevaluated;
8397 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008398 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008399
Sebastian Redl623ea822011-05-19 05:13:44 +00008400 // FIXME: If the destructor has a body that could throw, and the newly created
8401 // spec doesn't allow exceptions, we should emit a warning, because this
8402 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008403 // However, we don't have a body or an exception specification yet, so it
8404 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008405}
8406
Richard Smith41ae3282012-11-14 00:50:40 +00008407/// When generating a defaulted copy or move assignment operator, if a field
8408/// should be copied with __builtin_memcpy rather than via explicit assignments,
8409/// do so. This optimization only applies for arrays of scalars, and for arrays
8410/// of class type where the selected copy/move-assignment operator is trivial.
8411static StmtResult
8412buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8413 Expr *To, Expr *From) {
8414 // Compute the size of the memory buffer to be copied.
8415 QualType SizeType = S.Context.getSizeType();
8416 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8417 S.Context.getTypeSizeInChars(T).getQuantity());
8418
8419 // Take the address of the field references for "from" and "to". We
8420 // directly construct UnaryOperators here because semantic analysis
8421 // does not permit us to take the address of an xvalue.
8422 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8423 S.Context.getPointerType(From->getType()),
8424 VK_RValue, OK_Ordinary, Loc);
8425 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8426 S.Context.getPointerType(To->getType()),
8427 VK_RValue, OK_Ordinary, Loc);
8428
8429 const Type *E = T->getBaseElementTypeUnsafe();
8430 bool NeedsCollectableMemCpy =
8431 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8432
8433 // Create a reference to the __builtin_objc_memmove_collectable function
8434 StringRef MemCpyName = NeedsCollectableMemCpy ?
8435 "__builtin_objc_memmove_collectable" :
8436 "__builtin_memcpy";
8437 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8438 Sema::LookupOrdinaryName);
8439 S.LookupName(R, S.TUScope, true);
8440
8441 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8442 if (!MemCpy)
8443 // Something went horribly wrong earlier, and we will have complained
8444 // about it.
8445 return StmtError();
8446
8447 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8448 VK_RValue, Loc, 0);
8449 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8450
8451 Expr *CallArgs[] = {
8452 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8453 };
8454 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8455 Loc, CallArgs, Loc);
8456
8457 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8458 return S.Owned(Call.takeAs<Stmt>());
8459}
8460
Sebastian Redl22653ba2011-08-30 19:58:05 +00008461/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008462/// \c To.
8463///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008464/// This routine is used to copy/move the members of a class with an
8465/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008466/// copied are arrays, this routine builds for loops to copy them.
8467///
8468/// \param S The Sema object used for type-checking.
8469///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008470/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008471///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008472/// \param T The type of the expressions being copied/moved. Both expressions
8473/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008474///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008475/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008476///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008477/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008478///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008479/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008480/// Otherwise, it's a non-static member subobject.
8481///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008482/// \param Copying Whether we're copying or moving.
8483///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008484/// \param Depth Internal parameter recording the depth of the recursion.
8485///
Richard Smith41ae3282012-11-14 00:50:40 +00008486/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8487/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008488static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008489buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8490 Expr *To, Expr *From,
8491 bool CopyingBaseSubobject, bool Copying,
8492 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008493 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008494 // Each subobject is assigned in the manner appropriate to its type:
8495 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008496 // - if the subobject is of class type, as if by a call to operator= with
8497 // the subobject as the object expression and the corresponding
8498 // subobject of x as a single function argument (as if by explicit
8499 // qualification; that is, ignoring any possible virtual overriding
8500 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00008501 //
8502 // C++03 [class.copy]p13:
8503 // - if the subobject is of class type, the copy assignment operator for
8504 // the class is used (as if by explicit qualification; that is,
8505 // ignoring any possible virtual overriding functions in more derived
8506 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008507 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8508 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00008509
Douglas Gregorb139cd52010-05-01 20:49:11 +00008510 // Look for operator=.
8511 DeclarationName Name
8512 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8513 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8514 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008515
Richard Smith52c0b582012-11-13 00:54:12 +00008516 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8517 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008518 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00008519 LookupResult::Filter F = OpLookup.makeFilter();
8520 while (F.hasNext()) {
8521 NamedDecl *D = F.next();
8522 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8523 if (Method->isCopyAssignmentOperator() ||
8524 (!Copying && Method->isMoveAssignmentOperator()))
8525 continue;
8526
8527 F.erase();
8528 }
8529 F.done();
John McCallab8c2732010-03-16 06:11:48 +00008530 }
Richard Smith52c0b582012-11-13 00:54:12 +00008531
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008532 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00008533 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008534 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00008535 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008536 // ambiguities), we need to cast "this" to that subobject type; to
8537 // ensure that we don't go through the virtual call mechanism, we need
8538 // to qualify the operator= name with the base class (see below). However,
8539 // this means that if the base class has a protected copy assignment
8540 // operator, the protected member access check will fail. So, we
8541 // rewrite "protected" access to "public" access in this case, since we
8542 // know by construction that we're calling from a derived class.
8543 if (CopyingBaseSubobject) {
8544 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8545 L != LEnd; ++L) {
8546 if (L.getAccess() == AS_protected)
8547 L.setAccess(AS_public);
8548 }
8549 }
Richard Smith52c0b582012-11-13 00:54:12 +00008550
Douglas Gregorb139cd52010-05-01 20:49:11 +00008551 // Create the nested-name-specifier that will be used to qualify the
8552 // reference to operator=; this is required to suppress the virtual
8553 // call mechanism.
8554 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00008555 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00008556 SS.MakeTrivial(S.Context,
8557 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00008558 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00008559 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00008560
Douglas Gregorb139cd52010-05-01 20:49:11 +00008561 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00008562 ExprResult OpEqualRef
Richard Smith52c0b582012-11-13 00:54:12 +00008563 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008564 /*TemplateKWLoc=*/SourceLocation(),
8565 /*FirstQualifierInScope=*/0,
8566 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00008567 /*TemplateArgs=*/0,
8568 /*SuppressQualifierCheck=*/true);
8569 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008570 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00008571
Douglas Gregorb139cd52010-05-01 20:49:11 +00008572 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00008573
Richard Smith52c0b582012-11-13 00:54:12 +00008574 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008575 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00008576 Loc, From, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008577 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008578 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00008579
Richard Smith41ae3282012-11-14 00:50:40 +00008580 // If we built a call to a trivial 'operator=' while copying an array,
8581 // bail out. We'll replace the whole shebang with a memcpy.
8582 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8583 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8584 return StmtResult((Stmt*)0);
8585
Richard Smith52c0b582012-11-13 00:54:12 +00008586 // Convert to an expression-statement, and clean up any produced
8587 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00008588 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008589 }
John McCallab8c2732010-03-16 06:11:48 +00008590
Richard Smith52c0b582012-11-13 00:54:12 +00008591 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00008592 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00008593 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008594 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00008595 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008596 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008597 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00008598 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008599 }
Richard Smith52c0b582012-11-13 00:54:12 +00008600
8601 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00008602 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00008603
Douglas Gregorb139cd52010-05-01 20:49:11 +00008604 // Construct a loop over the array bounds, e.g.,
8605 //
8606 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8607 //
8608 // that will copy each of the array elements.
8609 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00008610
Douglas Gregorb139cd52010-05-01 20:49:11 +00008611 // Create the iteration variable.
8612 IdentifierInfo *IterationVarName = 0;
8613 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008614 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008615 llvm::raw_svector_ostream OS(Str);
8616 OS << "__i" << Depth;
8617 IterationVarName = &S.Context.Idents.get(OS.str());
8618 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00008619 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00008620 IterationVarName, SizeType,
8621 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008622 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00008623
Douglas Gregorb139cd52010-05-01 20:49:11 +00008624 // Initialize the iteration variable to zero.
8625 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008626 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00008627
8628 // Create a reference to the iteration variable; we'll use this several
8629 // times throughout.
8630 Expr *IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00008631 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008632 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00008633 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8634 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8635
Douglas Gregorb139cd52010-05-01 20:49:11 +00008636 // Create the DeclStmt that holds the iteration variable.
8637 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008638
Douglas Gregorb139cd52010-05-01 20:49:11 +00008639 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00008640 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00008641 IterationVarRefRVal,
8642 Loc));
John McCallb268a282010-08-23 23:25:46 +00008643 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00008644 IterationVarRefRVal,
8645 Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00008646 if (!Copying) // Cast to rvalue
8647 From = CastForMoving(S, From);
8648
8649 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00008650 StmtResult Copy =
8651 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8652 To, From, CopyingBaseSubobject,
8653 Copying, Depth + 1);
8654 // Bail out if copying fails or if we determined that we should use memcpy.
8655 if (Copy.isInvalid() || !Copy.get())
8656 return Copy;
8657
8658 // Create the comparison against the array bound.
8659 llvm::APInt Upper
8660 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8661 Expr *Comparison
8662 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8663 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8664 BO_NE, S.Context.BoolTy,
8665 VK_RValue, OK_Ordinary, Loc, false);
8666
8667 // Create the pre-increment of the iteration variable.
8668 Expr *Increment
8669 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8670 VK_LValue, OK_Ordinary, Loc);
8671
Douglas Gregorb139cd52010-05-01 20:49:11 +00008672 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00008673 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00008674 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00008675 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00008676 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008677}
8678
Richard Smith41ae3282012-11-14 00:50:40 +00008679static StmtResult
8680buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8681 Expr *To, Expr *From,
8682 bool CopyingBaseSubobject, bool Copying) {
8683 // Maybe we should use a memcpy?
8684 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8685 T.isTriviallyCopyableType(S.Context))
8686 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8687
8688 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8689 CopyingBaseSubobject,
8690 Copying, 0));
8691
8692 // If we ended up picking a trivial assignment operator for an array of a
8693 // non-trivially-copyable class type, just emit a memcpy.
8694 if (!Result.isInvalid() && !Result.get())
8695 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8696
8697 return Result;
8698}
8699
Richard Smithd3b5c9082012-07-27 04:22:15 +00008700Sema::ImplicitExceptionSpecification
8701Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8702 CXXRecordDecl *ClassDecl = MD->getParent();
8703
8704 ImplicitExceptionSpecification ExceptSpec(*this);
8705 if (ClassDecl->isInvalidDecl())
8706 return ExceptSpec;
8707
8708 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8709 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8710 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8711
Douglas Gregor68e11362010-07-01 17:48:08 +00008712 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00008713 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00008714 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00008715
8716 // It is unspecified whether or not an implicit copy assignment operator
8717 // attempts to deduplicate calls to assignment operators of virtual bases are
8718 // made. As such, this exception specification is effectively unspecified.
8719 // Based on a similar decision made for constness in C++0x, we're erring on
8720 // the side of assuming such calls to be made regardless of whether they
8721 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00008722 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8723 BaseEnd = ClassDecl->bases_end();
8724 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008725 if (Base->isVirtual())
8726 continue;
8727
Douglas Gregor330b9cf2010-07-02 21:50:04 +00008728 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00008729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008730 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8731 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00008732 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00008733 }
Alexis Hunt491ec602011-06-21 23:42:56 +00008734
8735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8736 BaseEnd = ClassDecl->vbases_end();
8737 Base != BaseEnd; ++Base) {
8738 CXXRecordDecl *BaseClassDecl
8739 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8740 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8741 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00008742 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00008743 }
8744
Douglas Gregor68e11362010-07-01 17:48:08 +00008745 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8746 FieldEnd = ClassDecl->field_end();
8747 Field != FieldEnd;
8748 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00008749 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00008750 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8751 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00008752 LookupCopyingAssignment(FieldClassDecl,
8753 ArgQuals | FieldType.getCVRQualifiers(),
8754 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00008755 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008756 }
Douglas Gregor68e11362010-07-01 17:48:08 +00008757 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008758
Richard Smithd3b5c9082012-07-27 04:22:15 +00008759 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00008760}
8761
8762CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8763 // Note: The following rules are largely analoguous to the copy
8764 // constructor rules. Note that virtual bases are not taken into account
8765 // for determining the argument type of the operator. Note also that
8766 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00008767 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00008768
Richard Smith8bf22e52012-11-29 01:34:07 +00008769 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8770 if (DSM.isAlreadyBeingDeclared())
8771 return 0;
8772
Alexis Hunt119f3652011-05-14 05:23:20 +00008773 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8774 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00008775 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8776 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00008777 ArgType = ArgType.withConst();
8778 ArgType = Context.getLValueReferenceType(ArgType);
8779
Richard Smith99005e62013-05-07 03:19:20 +00008780 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8781 CXXCopyAssignment,
8782 Const);
8783
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00008784 // An implicitly-declared copy assignment operator is an inline public
8785 // member of its class.
8786 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008787 SourceLocation ClassLoc = ClassDecl->getLocation();
8788 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00008789 CXXMethodDecl *CopyAssignment =
8790 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8791 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8792 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00008793 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00008794 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00008795 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008796
8797 // Build an exception specification pointing back at this member.
8798 FunctionProtoType::ExtProtoInfo EPI;
8799 EPI.ExceptionSpecType = EST_Unevaluated;
8800 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rose5c382722013-03-08 21:51:21 +00008801 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008802
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00008803 // Add the parameter to the operator.
8804 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008805 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00008806 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008807 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008808 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00008809
Richard Smith6b02d462012-12-08 08:32:28 +00008810 AddOverriddenMethods(ClassDecl, CopyAssignment);
8811
8812 CopyAssignment->setTrivial(
8813 ClassDecl->needsOverloadResolutionForCopyAssignment()
8814 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8815 : ClassDecl->hasTrivialCopyAssignment());
8816
Richard Smith99005e62013-05-07 03:19:20 +00008817 // C++11 [class.copy]p19:
Nico Weber94e746d2012-01-23 03:19:29 +00008818 // .... If the class definition does not explicitly declare a copy
8819 // assignment operator, there is no user-declared move constructor, and
8820 // there is no user-declared move assignment operator, a copy assignment
8821 // operator is implicitly declared as defaulted.
Richard Smith852265f2012-03-30 20:53:28 +00008822 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00008823 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00008824
Richard Smith6b02d462012-12-08 08:32:28 +00008825 // Note that we have added this copy-assignment operator.
8826 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8827
8828 if (Scope *S = getScopeForContext(ClassDecl))
8829 PushOnScopeChains(CopyAssignment, S, false);
8830 ClassDecl->addDecl(CopyAssignment);
8831
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00008832 return CopyAssignment;
8833}
8834
Richard Smithd577fbb2013-06-13 03:23:42 +00008835/// Diagnose an implicit copy operation for a class which is odr-used, but
8836/// which is deprecated because the class has a user-declared copy constructor,
8837/// copy assignment operator, or destructor.
8838static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8839 SourceLocation UseLoc) {
8840 assert(CopyOp->isImplicit());
8841
8842 CXXRecordDecl *RD = CopyOp->getParent();
8843 CXXMethodDecl *UserDeclaredOperation = 0;
8844
8845 // In Microsoft mode, assignment operations don't affect constructors and
8846 // vice versa.
8847 if (RD->hasUserDeclaredDestructor()) {
8848 UserDeclaredOperation = RD->getDestructor();
8849 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8850 RD->hasUserDeclaredCopyConstructor() &&
8851 !S.getLangOpts().MicrosoftMode) {
8852 // Find any user-declared copy constructor.
8853 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8854 E = RD->ctor_end(); I != E; ++I) {
8855 if (I->isCopyConstructor()) {
8856 UserDeclaredOperation = *I;
8857 break;
8858 }
8859 }
8860 assert(UserDeclaredOperation);
8861 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8862 RD->hasUserDeclaredCopyAssignment() &&
8863 !S.getLangOpts().MicrosoftMode) {
8864 // Find any user-declared move assignment operator.
8865 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8866 E = RD->method_end(); I != E; ++I) {
8867 if (I->isCopyAssignmentOperator()) {
8868 UserDeclaredOperation = *I;
8869 break;
8870 }
8871 }
8872 assert(UserDeclaredOperation);
8873 }
8874
8875 if (UserDeclaredOperation) {
8876 S.Diag(UserDeclaredOperation->getLocation(),
8877 diag::warn_deprecated_copy_operation)
8878 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8879 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8880 S.Diag(UseLoc, diag::note_member_synthesized_at)
8881 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8882 : Sema::CXXCopyAssignment)
8883 << RD;
8884 }
8885}
8886
Douglas Gregorb139cd52010-05-01 20:49:11 +00008887void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8888 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00008889 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00008890 CopyAssignOperator->isOverloadedOperator() &&
8891 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00008892 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8893 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00008894 "DefineImplicitCopyAssignment called for wrong function");
8895
8896 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8897
8898 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8899 CopyAssignOperator->setInvalidDecl();
8900 return;
8901 }
Richard Smithd577fbb2013-06-13 03:23:42 +00008902
8903 // C++11 [class.copy]p18:
8904 // The [definition of an implicitly declared copy assignment operator] is
8905 // deprecated if the class has a user-declared copy constructor or a
8906 // user-declared destructor.
8907 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8908 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8909
Douglas Gregorb139cd52010-05-01 20:49:11 +00008910 CopyAssignOperator->setUsed();
8911
Eli Friedmaneaf34142012-10-18 20:14:08 +00008912 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008913 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008914
8915 // C++0x [class.copy]p30:
8916 // The implicitly-defined or explicitly-defaulted copy assignment operator
8917 // for a non-union class X performs memberwise copy assignment of its
8918 // subobjects. The direct base classes of X are assigned first, in the
8919 // order of their declaration in the base-specifier-list, and then the
8920 // immediate non-static data members of X are assigned, in the order in
8921 // which they were declared in the class definition.
8922
8923 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00008924 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008925
8926 // The parameter for the "other" object, which we are copying from.
8927 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8928 Qualifiers OtherQuals = Other->getType().getQualifiers();
8929 QualType OtherRefType = Other->getType();
8930 if (const LValueReferenceType *OtherRef
8931 = OtherRefType->getAs<LValueReferenceType>()) {
8932 OtherRefType = OtherRef->getPointeeType();
8933 OtherQuals = OtherRefType.getQualifiers();
8934 }
8935
8936 // Our location for everything implicitly-generated.
8937 SourceLocation Loc = CopyAssignOperator->getLocation();
8938
8939 // Construct a reference to the "other" object. We'll be using this
8940 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00008941 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008942 assert(OtherRef && "Reference to parameter cannot fail!");
8943
8944 // Construct the "this" pointer. We'll be using this throughout the generated
8945 // ASTs.
8946 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8947 assert(This && "Reference to this cannot fail!");
8948
8949 // Assign base classes.
8950 bool Invalid = false;
8951 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8952 E = ClassDecl->bases_end(); Base != E; ++Base) {
8953 // Form the assignment:
8954 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8955 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008956 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008957 Invalid = true;
8958 continue;
8959 }
8960
John McCallcf142162010-08-07 06:22:56 +00008961 CXXCastPath BasePath;
8962 BasePath.push_back(Base);
8963
Douglas Gregorb139cd52010-05-01 20:49:11 +00008964 // Construct the "from" expression, which is an implicit cast to the
8965 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00008966 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00008967 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8968 CK_UncheckedDerivedToBase,
8969 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008970
8971 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00008972 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008973
8974 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00008975 To = ImpCastExprToType(To.take(),
8976 Context.getCVRQualifiedType(BaseType,
8977 CopyAssignOperator->getTypeQualifiers()),
8978 CK_UncheckedDerivedToBase,
8979 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008980
8981 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00008982 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00008983 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008984 /*CopyingBaseSubobject=*/true,
8985 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008986 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008987 Diag(CurrentLocation, diag::note_member_synthesized_at)
8988 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8989 CopyAssignOperator->setInvalidDecl();
8990 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008991 }
8992
8993 // Success! Record the copy.
8994 Statements.push_back(Copy.takeAs<Expr>());
8995 }
8996
Douglas Gregorb139cd52010-05-01 20:49:11 +00008997 // Assign non-static members.
8998 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8999 FieldEnd = ClassDecl->field_end();
9000 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009001 if (Field->isUnnamedBitfield())
9002 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009003
9004 if (Field->isInvalidDecl()) {
9005 Invalid = true;
9006 continue;
9007 }
9008
Douglas Gregorb139cd52010-05-01 20:49:11 +00009009 // Check for members of reference type; we can't copy those.
9010 if (Field->getType()->isReferenceType()) {
9011 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9012 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9013 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009014 Diag(CurrentLocation, diag::note_member_synthesized_at)
9015 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009016 Invalid = true;
9017 continue;
9018 }
9019
9020 // Check for members of const-qualified, non-class type.
9021 QualType BaseType = Context.getBaseElementType(Field->getType());
9022 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9023 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9024 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9025 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009026 Diag(CurrentLocation, diag::note_member_synthesized_at)
9027 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009028 Invalid = true;
9029 continue;
9030 }
John McCall1b1a1db2011-06-17 00:18:42 +00009031
9032 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009033 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9034 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009035
9036 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009037 if (FieldType->isIncompleteArrayType()) {
9038 assert(ClassDecl->hasFlexibleArrayMember() &&
9039 "Incomplete array type is not valid");
9040 continue;
9041 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009042
9043 // Build references to the field in the object we're copying from and to.
9044 CXXScopeSpec SS; // Intentionally empty
9045 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9046 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009047 MemberLookup.addDecl(*Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009048 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00009049 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00009050 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009051 SS, SourceLocation(), 0,
9052 MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00009053 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00009054 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009055 SS, SourceLocation(), 0,
9056 MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009057 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9058 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregorb139cd52010-05-01 20:49:11 +00009059
Douglas Gregorb139cd52010-05-01 20:49:11 +00009060 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009061 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009062 To.get(), From.get(),
9063 /*CopyingBaseSubobject=*/false,
9064 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009065 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009066 Diag(CurrentLocation, diag::note_member_synthesized_at)
9067 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9068 CopyAssignOperator->setInvalidDecl();
9069 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009070 }
9071
9072 // Success! Record the copy.
9073 Statements.push_back(Copy.takeAs<Stmt>());
9074 }
9075
9076 if (!Invalid) {
9077 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00009078 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009079
John McCalldadc5752010-08-24 06:29:42 +00009080 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009081 if (Return.isInvalid())
9082 Invalid = true;
9083 else {
9084 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009085
9086 if (Trap.hasErrorOccurred()) {
9087 Diag(CurrentLocation, diag::note_member_synthesized_at)
9088 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9089 Invalid = true;
9090 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009091 }
9092 }
9093
9094 if (Invalid) {
9095 CopyAssignOperator->setInvalidDecl();
9096 return;
9097 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009098
9099 StmtResult Body;
9100 {
9101 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009102 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009103 /*isStmtExpr=*/false);
9104 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9105 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009106 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009107
9108 if (ASTMutationListener *L = getASTMutationListener()) {
9109 L->CompletedImplicitDefinition(CopyAssignOperator);
9110 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009111}
9112
Sebastian Redl22653ba2011-08-30 19:58:05 +00009113Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009114Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9115 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009116
Richard Smithd3b5c9082012-07-27 04:22:15 +00009117 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009118 if (ClassDecl->isInvalidDecl())
9119 return ExceptSpec;
9120
9121 // C++0x [except.spec]p14:
9122 // An implicitly declared special member function (Clause 12) shall have an
9123 // exception-specification. [...]
9124
9125 // It is unspecified whether or not an implicit move assignment operator
9126 // attempts to deduplicate calls to assignment operators of virtual bases are
9127 // made. As such, this exception specification is effectively unspecified.
9128 // Based on a similar decision made for constness in C++0x, we're erring on
9129 // the side of assuming such calls to be made regardless of whether they
9130 // actually happen.
9131 // Note that a move constructor is not implicitly declared when there are
9132 // virtual bases, but it can still be user-declared and explicitly defaulted.
9133 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9134 BaseEnd = ClassDecl->bases_end();
9135 Base != BaseEnd; ++Base) {
9136 if (Base->isVirtual())
9137 continue;
9138
9139 CXXRecordDecl *BaseClassDecl
9140 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9141 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009142 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009143 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009144 }
9145
9146 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9147 BaseEnd = ClassDecl->vbases_end();
9148 Base != BaseEnd; ++Base) {
9149 CXXRecordDecl *BaseClassDecl
9150 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9151 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009152 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009153 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009154 }
9155
9156 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9157 FieldEnd = ClassDecl->field_end();
9158 Field != FieldEnd;
9159 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009160 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009161 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009162 if (CXXMethodDecl *MoveAssign =
9163 LookupMovingAssignment(FieldClassDecl,
9164 FieldType.getCVRQualifiers(),
9165 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009166 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009167 }
9168 }
9169
9170 return ExceptSpec;
9171}
9172
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009173/// Determine whether the class type has any direct or indirect virtual base
9174/// classes which have a non-trivial move assignment operator.
9175static bool
9176hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9177 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9178 BaseEnd = ClassDecl->vbases_end();
9179 Base != BaseEnd; ++Base) {
9180 CXXRecordDecl *BaseClass =
9181 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9182
9183 // Try to declare the move assignment. If it would be deleted, then the
9184 // class does not have a non-trivial move assignment.
9185 if (BaseClass->needsImplicitMoveAssignment())
9186 S.DeclareImplicitMoveAssignment(BaseClass);
9187
Richard Smith16488472012-11-16 00:53:38 +00009188 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009189 return true;
9190 }
9191
9192 return false;
9193}
9194
9195/// Determine whether the given type either has a move constructor or is
9196/// trivially copyable.
9197static bool
9198hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9199 Type = S.Context.getBaseElementType(Type);
9200
9201 // FIXME: Technically, non-trivially-copyable non-class types, such as
9202 // reference types, are supposed to return false here, but that appears
9203 // to be a standard defect.
9204 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidis8e502972012-10-10 16:14:06 +00009205 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009206 return true;
9207
9208 if (Type.isTriviallyCopyableType(S.Context))
9209 return true;
9210
9211 if (IsConstructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00009212 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9213 // give the right answer.
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009214 if (ClassDecl->needsImplicitMoveConstructor())
9215 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smith2be35f52012-12-01 02:35:44 +00009216 return ClassDecl->hasMoveConstructor();
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009217 }
9218
Richard Smith2be35f52012-12-01 02:35:44 +00009219 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9220 // give the right answer.
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009221 if (ClassDecl->needsImplicitMoveAssignment())
9222 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smith2be35f52012-12-01 02:35:44 +00009223 return ClassDecl->hasMoveAssignment();
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009224}
9225
9226/// Determine whether all non-static data members and direct or virtual bases
9227/// of class \p ClassDecl have either a move operation, or are trivially
9228/// copyable.
9229static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9230 bool IsConstructor) {
9231 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9232 BaseEnd = ClassDecl->bases_end();
9233 Base != BaseEnd; ++Base) {
9234 if (Base->isVirtual())
9235 continue;
9236
9237 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9238 return false;
9239 }
9240
9241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9242 BaseEnd = ClassDecl->vbases_end();
9243 Base != BaseEnd; ++Base) {
9244 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9245 return false;
9246 }
9247
9248 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9249 FieldEnd = ClassDecl->field_end();
9250 Field != FieldEnd; ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009251 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009252 return false;
9253 }
9254
9255 return true;
9256}
9257
Sebastian Redl22653ba2011-08-30 19:58:05 +00009258CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009259 // C++11 [class.copy]p20:
9260 // If the definition of a class X does not explicitly declare a move
9261 // assignment operator, one will be implicitly declared as defaulted
9262 // if and only if:
9263 //
9264 // - [first 4 bullets]
9265 assert(ClassDecl->needsImplicitMoveAssignment());
9266
Richard Smith8bf22e52012-11-29 01:34:07 +00009267 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9268 if (DSM.isAlreadyBeingDeclared())
9269 return 0;
9270
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009271 // [Checked after we build the declaration]
9272 // - the move assignment operator would not be implicitly defined as
9273 // deleted,
9274
9275 // [DR1402]:
9276 // - X has no direct or indirect virtual base class with a non-trivial
9277 // move assignment operator, and
9278 // - each of X's non-static data members and direct or virtual base classes
9279 // has a type that either has a move assignment operator or is trivially
9280 // copyable.
9281 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9282 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9283 ClassDecl->setFailedImplicitMoveAssignment();
9284 return 0;
9285 }
9286
Sebastian Redl22653ba2011-08-30 19:58:05 +00009287 // Note: The following rules are largely analoguous to the move
9288 // constructor rules.
9289
Sebastian Redl22653ba2011-08-30 19:58:05 +00009290 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9291 QualType RetType = Context.getLValueReferenceType(ArgType);
9292 ArgType = Context.getRValueReferenceType(ArgType);
9293
Richard Smith99005e62013-05-07 03:19:20 +00009294 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9295 CXXMoveAssignment,
9296 false);
9297
Sebastian Redl22653ba2011-08-30 19:58:05 +00009298 // An implicitly-declared move assignment operator is an inline public
9299 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009300 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9301 SourceLocation ClassLoc = ClassDecl->getLocation();
9302 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009303 CXXMethodDecl *MoveAssignment =
9304 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9305 /*TInfo=*/0, /*StorageClass=*/SC_None,
9306 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009307 MoveAssignment->setAccess(AS_public);
9308 MoveAssignment->setDefaulted();
9309 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009310
Richard Smithd3b5c9082012-07-27 04:22:15 +00009311 // Build an exception specification pointing back at this member.
9312 FunctionProtoType::ExtProtoInfo EPI;
9313 EPI.ExceptionSpecType = EST_Unevaluated;
9314 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rose5c382722013-03-08 21:51:21 +00009315 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009316
Sebastian Redl22653ba2011-08-30 19:58:05 +00009317 // Add the parameter to the operator.
9318 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9319 ClassLoc, ClassLoc, /*Id=*/0,
9320 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009321 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009322 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009323
Richard Smith6b02d462012-12-08 08:32:28 +00009324 AddOverriddenMethods(ClassDecl, MoveAssignment);
9325
9326 MoveAssignment->setTrivial(
9327 ClassDecl->needsOverloadResolutionForMoveAssignment()
9328 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9329 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009330
9331 // C++0x [class.copy]p9:
9332 // If the definition of a class X does not explicitly declare a move
9333 // assignment operator, one will be implicitly declared as defaulted if and
9334 // only if:
9335 // [...]
9336 // - the move assignment operator would not be implicitly defined as
9337 // deleted.
Richard Smithd951a1d2012-02-18 02:02:13 +00009338 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009339 // Cache this result so that we don't try to generate this over and over
9340 // on every lookup, leaking memory and wasting time.
9341 ClassDecl->setFailedImplicitMoveAssignment();
9342 return 0;
9343 }
9344
Richard Smith6b02d462012-12-08 08:32:28 +00009345 // Note that we have added this copy-assignment operator.
9346 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9347
Sebastian Redl22653ba2011-08-30 19:58:05 +00009348 if (Scope *S = getScopeForContext(ClassDecl))
9349 PushOnScopeChains(MoveAssignment, S, false);
9350 ClassDecl->addDecl(MoveAssignment);
9351
Sebastian Redl22653ba2011-08-30 19:58:05 +00009352 return MoveAssignment;
9353}
9354
9355void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9356 CXXMethodDecl *MoveAssignOperator) {
9357 assert((MoveAssignOperator->isDefaulted() &&
9358 MoveAssignOperator->isOverloadedOperator() &&
9359 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009360 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9361 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009362 "DefineImplicitMoveAssignment called for wrong function");
9363
9364 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9365
9366 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9367 MoveAssignOperator->setInvalidDecl();
9368 return;
9369 }
9370
9371 MoveAssignOperator->setUsed();
9372
Eli Friedmaneaf34142012-10-18 20:14:08 +00009373 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009374 DiagnosticErrorTrap Trap(Diags);
9375
9376 // C++0x [class.copy]p28:
9377 // The implicitly-defined or move assignment operator for a non-union class
9378 // X performs memberwise move assignment of its subobjects. The direct base
9379 // classes of X are assigned first, in the order of their declaration in the
9380 // base-specifier-list, and then the immediate non-static data members of X
9381 // are assigned, in the order in which they were declared in the class
9382 // definition.
9383
9384 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009385 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009386
9387 // The parameter for the "other" object, which we are move from.
9388 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9389 QualType OtherRefType = Other->getType()->
9390 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009391 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009392 "Bad argument type of defaulted move assignment");
9393
9394 // Our location for everything implicitly-generated.
9395 SourceLocation Loc = MoveAssignOperator->getLocation();
9396
9397 // Construct a reference to the "other" object. We'll be using this
9398 // throughout the generated ASTs.
9399 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9400 assert(OtherRef && "Reference to parameter cannot fail!");
9401 // Cast to rvalue.
9402 OtherRef = CastForMoving(*this, OtherRef);
9403
9404 // Construct the "this" pointer. We'll be using this throughout the generated
9405 // ASTs.
9406 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9407 assert(This && "Reference to this cannot fail!");
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009408
Sebastian Redl22653ba2011-08-30 19:58:05 +00009409 // Assign base classes.
9410 bool Invalid = false;
9411 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9412 E = ClassDecl->bases_end(); Base != E; ++Base) {
9413 // Form the assignment:
9414 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9415 QualType BaseType = Base->getType().getUnqualifiedType();
9416 if (!BaseType->isRecordType()) {
9417 Invalid = true;
9418 continue;
9419 }
9420
9421 CXXCastPath BasePath;
9422 BasePath.push_back(Base);
9423
9424 // Construct the "from" expression, which is an implicit cast to the
9425 // appropriately-qualified base type.
9426 Expr *From = OtherRef;
9427 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00009428 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009429
9430 // Dereference "this".
9431 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9432
9433 // Implicitly cast "this" to the appropriately-qualified base type.
9434 To = ImpCastExprToType(To.take(),
9435 Context.getCVRQualifiedType(BaseType,
9436 MoveAssignOperator->getTypeQualifiers()),
9437 CK_UncheckedDerivedToBase,
9438 VK_LValue, &BasePath);
9439
9440 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009441 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009442 To.get(), From,
9443 /*CopyingBaseSubobject=*/true,
9444 /*Copying=*/false);
9445 if (Move.isInvalid()) {
9446 Diag(CurrentLocation, diag::note_member_synthesized_at)
9447 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9448 MoveAssignOperator->setInvalidDecl();
9449 return;
9450 }
9451
9452 // Success! Record the move.
9453 Statements.push_back(Move.takeAs<Expr>());
9454 }
9455
Sebastian Redl22653ba2011-08-30 19:58:05 +00009456 // Assign non-static members.
9457 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9458 FieldEnd = ClassDecl->field_end();
9459 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009460 if (Field->isUnnamedBitfield())
9461 continue;
9462
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009463 if (Field->isInvalidDecl()) {
9464 Invalid = true;
9465 continue;
9466 }
9467
Sebastian Redl22653ba2011-08-30 19:58:05 +00009468 // Check for members of reference type; we can't move those.
9469 if (Field->getType()->isReferenceType()) {
9470 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9471 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9472 Diag(Field->getLocation(), diag::note_declared_at);
9473 Diag(CurrentLocation, diag::note_member_synthesized_at)
9474 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9475 Invalid = true;
9476 continue;
9477 }
9478
9479 // Check for members of const-qualified, non-class type.
9480 QualType BaseType = Context.getBaseElementType(Field->getType());
9481 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9482 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9483 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9484 Diag(Field->getLocation(), diag::note_declared_at);
9485 Diag(CurrentLocation, diag::note_member_synthesized_at)
9486 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9487 Invalid = true;
9488 continue;
9489 }
9490
9491 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009492 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9493 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009494
9495 QualType FieldType = Field->getType().getNonReferenceType();
9496 if (FieldType->isIncompleteArrayType()) {
9497 assert(ClassDecl->hasFlexibleArrayMember() &&
9498 "Incomplete array type is not valid");
9499 continue;
9500 }
9501
9502 // Build references to the field in the object we're copying from and to.
9503 CXXScopeSpec SS; // Intentionally empty
9504 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9505 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009506 MemberLookup.addDecl(*Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009507 MemberLookup.resolveKind();
9508 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9509 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009510 SS, SourceLocation(), 0,
9511 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009512 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9513 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009514 SS, SourceLocation(), 0,
9515 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009516 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9517 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9518
9519 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9520 "Member reference with rvalue base must be rvalue except for reference "
9521 "members, which aren't allowed for move assignment.");
9522
Sebastian Redl22653ba2011-08-30 19:58:05 +00009523 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009524 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009525 To.get(), From.get(),
9526 /*CopyingBaseSubobject=*/false,
9527 /*Copying=*/false);
9528 if (Move.isInvalid()) {
9529 Diag(CurrentLocation, diag::note_member_synthesized_at)
9530 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9531 MoveAssignOperator->setInvalidDecl();
9532 return;
9533 }
Richard Smith11d19592012-11-12 23:33:00 +00009534
Sebastian Redl22653ba2011-08-30 19:58:05 +00009535 // Success! Record the copy.
9536 Statements.push_back(Move.takeAs<Stmt>());
9537 }
9538
9539 if (!Invalid) {
9540 // Add a "return *this;"
9541 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9542
9543 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9544 if (Return.isInvalid())
9545 Invalid = true;
9546 else {
9547 Statements.push_back(Return.takeAs<Stmt>());
9548
9549 if (Trap.hasErrorOccurred()) {
9550 Diag(CurrentLocation, diag::note_member_synthesized_at)
9551 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9552 Invalid = true;
9553 }
9554 }
9555 }
9556
9557 if (Invalid) {
9558 MoveAssignOperator->setInvalidDecl();
9559 return;
9560 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009561
9562 StmtResult Body;
9563 {
9564 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009565 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009566 /*isStmtExpr=*/false);
9567 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9568 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009569 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9570
9571 if (ASTMutationListener *L = getASTMutationListener()) {
9572 L->CompletedImplicitDefinition(MoveAssignOperator);
9573 }
9574}
9575
Richard Smithd3b5c9082012-07-27 04:22:15 +00009576Sema::ImplicitExceptionSpecification
9577Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9578 CXXRecordDecl *ClassDecl = MD->getParent();
9579
9580 ImplicitExceptionSpecification ExceptSpec(*this);
9581 if (ClassDecl->isInvalidDecl())
9582 return ExceptSpec;
9583
9584 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9585 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9586 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9587
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009588 // C++ [except.spec]p14:
9589 // An implicitly declared special member function (Clause 12) shall have an
9590 // exception-specification. [...]
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009591 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9592 BaseEnd = ClassDecl->bases_end();
9593 Base != BaseEnd;
9594 ++Base) {
9595 // Virtual bases are handled below.
9596 if (Base->isVirtual())
9597 continue;
9598
Douglas Gregora6d69502010-07-02 23:41:54 +00009599 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009600 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009601 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009602 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +00009603 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009604 }
9605 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9606 BaseEnd = ClassDecl->vbases_end();
9607 Base != BaseEnd;
9608 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00009609 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009610 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009611 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009612 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +00009613 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009614 }
9615 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9616 FieldEnd = ClassDecl->field_end();
9617 Field != FieldEnd;
9618 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009619 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00009620 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9621 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +00009622 LookupCopyingConstructor(FieldClassDecl,
9623 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +00009624 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009625 }
9626 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009627
Richard Smithd3b5c9082012-07-27 04:22:15 +00009628 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +00009629}
9630
9631CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9632 CXXRecordDecl *ClassDecl) {
9633 // C++ [class.copy]p4:
9634 // If the class definition does not explicitly declare a copy
9635 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +00009636 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +00009637
Richard Smith8bf22e52012-11-29 01:34:07 +00009638 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9639 if (DSM.isAlreadyBeingDeclared())
9640 return 0;
9641
Alexis Hunt913820d2011-05-13 06:10:58 +00009642 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9643 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +00009644 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +00009645 if (Const)
9646 ArgType = ArgType.withConst();
9647 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +00009648
Richard Smithb5800092012-06-10 05:43:50 +00009649 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9650 CXXCopyConstructor,
9651 Const);
9652
Douglas Gregor54be3392010-07-01 17:57:27 +00009653 DeclarationName Name
9654 = Context.DeclarationNames.getCXXConstructorName(
9655 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009656 SourceLocation ClassLoc = ClassDecl->getLocation();
9657 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00009658
9659 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00009660 // member of its class.
9661 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00009662 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00009663 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00009664 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +00009665 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00009666 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +00009667
Richard Smithd3b5c9082012-07-27 04:22:15 +00009668 // Build an exception specification pointing back at this member.
9669 FunctionProtoType::ExtProtoInfo EPI;
9670 EPI.ExceptionSpecType = EST_Unevaluated;
9671 EPI.ExceptionSpecDecl = CopyConstructor;
9672 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +00009673 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009674
Douglas Gregor54be3392010-07-01 17:57:27 +00009675 // Add the parameter to the constructor.
9676 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009677 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00009678 /*IdentifierInfo=*/0,
9679 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009680 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009681 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00009682
Richard Smith6b02d462012-12-08 08:32:28 +00009683 CopyConstructor->setTrivial(
9684 ClassDecl->needsOverloadResolutionForCopyConstructor()
9685 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9686 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +00009687
Nico Weber94e746d2012-01-23 03:19:29 +00009688 // C++11 [class.copy]p8:
9689 // ... If the class definition does not explicitly declare a copy
9690 // constructor, there is no user-declared move constructor, and there is no
9691 // user-declared move assignment operator, a copy constructor is implicitly
9692 // declared as defaulted.
Richard Smith852265f2012-03-30 20:53:28 +00009693 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009694 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009695
Richard Smith6b02d462012-12-08 08:32:28 +00009696 // Note that we have declared this constructor.
9697 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9698
9699 if (Scope *S = getScopeForContext(ClassDecl))
9700 PushOnScopeChains(CopyConstructor, S, false);
9701 ClassDecl->addDecl(CopyConstructor);
9702
Douglas Gregor54be3392010-07-01 17:57:27 +00009703 return CopyConstructor;
9704}
9705
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009706void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00009707 CXXConstructorDecl *CopyConstructor) {
9708 assert((CopyConstructor->isDefaulted() &&
9709 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009710 !CopyConstructor->doesThisDeclarationHaveABody() &&
9711 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009712 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00009713
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00009714 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009715 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009716
Richard Smithd577fbb2013-06-13 03:23:42 +00009717 // C++11 [class.copy]p7:
9718 // The [definition of an implicitly declared copy constructro] is
9719 // deprecated if the class has a user-declared copy assignment operator
9720 // or a user-declared destructor.
9721 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9722 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9723
Eli Friedmaneaf34142012-10-18 20:14:08 +00009724 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009725 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009726
David Blaikie3fc2f912013-01-17 05:26:25 +00009727 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00009728 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00009729 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00009730 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00009731 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00009732 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009733 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregor94f9a482010-05-05 05:51:00 +00009734 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9735 CopyConstructor->getLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009736 MultiStmtArg(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00009737 /*isStmtExpr=*/false)
9738 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00009739 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00009740 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00009741
9742 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00009743 if (ASTMutationListener *L = getASTMutationListener()) {
9744 L->CompletedImplicitDefinition(CopyConstructor);
9745 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009746}
9747
Sebastian Redl22653ba2011-08-30 19:58:05 +00009748Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009749Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9750 CXXRecordDecl *ClassDecl = MD->getParent();
9751
Sebastian Redl22653ba2011-08-30 19:58:05 +00009752 // C++ [except.spec]p14:
9753 // An implicitly declared special member function (Clause 12) shall have an
9754 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00009755 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009756 if (ClassDecl->isInvalidDecl())
9757 return ExceptSpec;
9758
9759 // Direct base-class constructors.
9760 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9761 BEnd = ClassDecl->bases_end();
9762 B != BEnd; ++B) {
9763 if (B->isVirtual()) // Handled below.
9764 continue;
9765
9766 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9767 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +00009768 CXXConstructorDecl *Constructor =
9769 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009770 // If this is a deleted function, add it anyway. This might be conformant
9771 // with the standard. This might not. I'm not sure. It might not matter.
9772 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00009773 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009774 }
9775 }
9776
9777 // Virtual base-class constructors.
9778 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9779 BEnd = ClassDecl->vbases_end();
9780 B != BEnd; ++B) {
9781 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +00009783 CXXConstructorDecl *Constructor =
9784 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009785 // If this is a deleted function, add it anyway. This might be conformant
9786 // with the standard. This might not. I'm not sure. It might not matter.
9787 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00009788 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009789 }
9790 }
9791
9792 // Field constructors.
9793 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9794 FEnd = ClassDecl->field_end();
9795 F != FEnd; ++F) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009796 QualType FieldType = Context.getBaseElementType(F->getType());
9797 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9798 CXXConstructorDecl *Constructor =
9799 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009800 // If this is a deleted function, add it anyway. This might be conformant
9801 // with the standard. This might not. I'm not sure. It might not matter.
9802 // In particular, the problem is that this function never gets called. It
9803 // might just be ill-formed because this function attempts to refer to
9804 // a deleted function here.
9805 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00009806 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009807 }
9808 }
9809
9810 return ExceptSpec;
9811}
9812
9813CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9814 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009815 // C++11 [class.copy]p9:
9816 // If the definition of a class X does not explicitly declare a move
9817 // constructor, one will be implicitly declared as defaulted if and only if:
9818 //
9819 // - [first 4 bullets]
9820 assert(ClassDecl->needsImplicitMoveConstructor());
9821
Richard Smith8bf22e52012-11-29 01:34:07 +00009822 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9823 if (DSM.isAlreadyBeingDeclared())
9824 return 0;
9825
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009826 // [Checked after we build the declaration]
9827 // - the move assignment operator would not be implicitly defined as
9828 // deleted,
9829
9830 // [DR1402]:
9831 // - each of X's non-static data members and direct or virtual base classes
9832 // has a type that either has a move constructor or is trivially copyable.
9833 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9834 ClassDecl->setFailedImplicitMoveConstructor();
9835 return 0;
9836 }
9837
Sebastian Redl22653ba2011-08-30 19:58:05 +00009838 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9839 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009840
Richard Smithb5800092012-06-10 05:43:50 +00009841 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9842 CXXMoveConstructor,
9843 false);
9844
Sebastian Redl22653ba2011-08-30 19:58:05 +00009845 DeclarationName Name
9846 = Context.DeclarationNames.getCXXConstructorName(
9847 Context.getCanonicalType(ClassType));
9848 SourceLocation ClassLoc = ClassDecl->getLocation();
9849 DeclarationNameInfo NameInfo(Name, ClassLoc);
9850
Richard Smith99005e62013-05-07 03:19:20 +00009851 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +00009852 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00009853 // member of its class.
9854 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00009855 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00009856 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00009857 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009858 MoveConstructor->setAccess(AS_public);
9859 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +00009860
Richard Smithd3b5c9082012-07-27 04:22:15 +00009861 // Build an exception specification pointing back at this member.
9862 FunctionProtoType::ExtProtoInfo EPI;
9863 EPI.ExceptionSpecType = EST_Unevaluated;
9864 EPI.ExceptionSpecDecl = MoveConstructor;
9865 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +00009866 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009867
Sebastian Redl22653ba2011-08-30 19:58:05 +00009868 // Add the parameter to the constructor.
9869 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9870 ClassLoc, ClassLoc,
9871 /*IdentifierInfo=*/0,
9872 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009873 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009874 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009875
Richard Smith6b02d462012-12-08 08:32:28 +00009876 MoveConstructor->setTrivial(
9877 ClassDecl->needsOverloadResolutionForMoveConstructor()
9878 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9879 : ClassDecl->hasTrivialMoveConstructor());
9880
Sebastian Redl22653ba2011-08-30 19:58:05 +00009881 // C++0x [class.copy]p9:
9882 // If the definition of a class X does not explicitly declare a move
9883 // constructor, one will be implicitly declared as defaulted if and only if:
9884 // [...]
9885 // - the move constructor would not be implicitly defined as deleted.
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00009886 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009887 // Cache this result so that we don't try to generate this over and over
9888 // on every lookup, leaking memory and wasting time.
9889 ClassDecl->setFailedImplicitMoveConstructor();
9890 return 0;
9891 }
9892
9893 // Note that we have declared this constructor.
9894 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9895
9896 if (Scope *S = getScopeForContext(ClassDecl))
9897 PushOnScopeChains(MoveConstructor, S, false);
9898 ClassDecl->addDecl(MoveConstructor);
9899
9900 return MoveConstructor;
9901}
9902
9903void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9904 CXXConstructorDecl *MoveConstructor) {
9905 assert((MoveConstructor->isDefaulted() &&
9906 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009907 !MoveConstructor->doesThisDeclarationHaveABody() &&
9908 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009909 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9910
9911 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9912 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9913
Eli Friedmaneaf34142012-10-18 20:14:08 +00009914 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009915 DiagnosticErrorTrap Trap(Diags);
9916
David Blaikie3fc2f912013-01-17 05:26:25 +00009917 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +00009918 Trap.hasErrorOccurred()) {
9919 Diag(CurrentLocation, diag::note_member_synthesized_at)
9920 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9921 MoveConstructor->setInvalidDecl();
9922 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009923 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009924 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9925 MoveConstructor->getLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009926 MultiStmtArg(),
Sebastian Redl22653ba2011-08-30 19:58:05 +00009927 /*isStmtExpr=*/false)
9928 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00009929 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009930 }
9931
9932 MoveConstructor->setUsed();
9933
9934 if (ASTMutationListener *L = getASTMutationListener()) {
9935 L->CompletedImplicitDefinition(MoveConstructor);
9936 }
9937}
9938
Douglas Gregor74f7d502012-02-15 19:33:52 +00009939bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9940 return FD->isDeleted() &&
9941 (FD->isDefaulted() || FD->isImplicit()) &&
9942 isa<CXXMethodDecl>(FD);
9943}
Douglas Gregord3b672c2012-02-16 01:06:16 +00009944
Douglas Gregor355efbb2012-02-17 03:02:34 +00009945/// \brief Mark the call operator of the given lambda closure type as "used".
9946static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9947 CXXMethodDecl *CallOperator
Douglas Gregored90df32012-02-22 05:02:47 +00009948 = cast<CXXMethodDecl>(
David Blaikieff7d47a2012-12-19 00:45:41 +00009949 Lambda->lookup(
9950 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor355efbb2012-02-17 03:02:34 +00009951 CallOperator->setReferenced();
9952 CallOperator->setUsed();
9953}
9954
Douglas Gregord3b672c2012-02-16 01:06:16 +00009955void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9956 SourceLocation CurrentLocation,
9957 CXXConversionDecl *Conv)
9958{
Douglas Gregor355efbb2012-02-17 03:02:34 +00009959 CXXRecordDecl *Lambda = Conv->getParent();
9960
9961 // Make sure that the lambda call operator is marked used.
9962 markLambdaCallOperatorUsed(*this, Lambda);
9963
Douglas Gregord3b672c2012-02-16 01:06:16 +00009964 Conv->setUsed();
9965
Eli Friedmaneaf34142012-10-18 20:14:08 +00009966 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +00009967 DiagnosticErrorTrap Trap(Diags);
9968
Douglas Gregor355efbb2012-02-17 03:02:34 +00009969 // Return the address of the __invoke function.
9970 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9971 CXXMethodDecl *Invoke
David Blaikieff7d47a2012-12-19 00:45:41 +00009972 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor355efbb2012-02-17 03:02:34 +00009973 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9974 VK_LValue, Conv->getLocation()).take();
9975 assert(FunctionRef && "Can't refer to __invoke function?");
9976 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Webera2a0eb92012-12-29 20:03:39 +00009977 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor355efbb2012-02-17 03:02:34 +00009978 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +00009979 Conv->getLocation()));
Douglas Gregor355efbb2012-02-17 03:02:34 +00009980
9981 // Fill in the __invoke function with a dummy implementation. IR generation
9982 // will fill in the actual details.
9983 Invoke->setUsed();
9984 Invoke->setReferenced();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009985 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregord3b672c2012-02-16 01:06:16 +00009986
9987 if (ASTMutationListener *L = getASTMutationListener()) {
9988 L->CompletedImplicitDefinition(Conv);
Douglas Gregor355efbb2012-02-17 03:02:34 +00009989 L->CompletedImplicitDefinition(Invoke);
Douglas Gregord3b672c2012-02-16 01:06:16 +00009990 }
9991}
9992
9993void Sema::DefineImplicitLambdaToBlockPointerConversion(
9994 SourceLocation CurrentLocation,
9995 CXXConversionDecl *Conv)
9996{
9997 Conv->setUsed();
9998
Eli Friedmaneaf34142012-10-18 20:14:08 +00009999 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010000 DiagnosticErrorTrap Trap(Diags);
10001
Douglas Gregored90df32012-02-22 05:02:47 +000010002 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010003 Expr *This = ActOnCXXThis(CurrentLocation).take();
10004 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010005
Eli Friedman98b01ed2012-03-01 04:01:32 +000010006 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10007 Conv->getLocation(),
10008 Conv, DerefThis);
10009
10010 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10011 // behavior. Note that only the general conversion function does this
10012 // (since it's unusable otherwise); in the case where we inline the
10013 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010014 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010015 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10016 CK_CopyAndAutoreleaseBlockObject,
10017 BuildBlock.get(), 0, VK_RValue);
10018
10019 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010020 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010021 Conv->setInvalidDecl();
10022 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010023 }
Douglas Gregored90df32012-02-22 05:02:47 +000010024
Douglas Gregored90df32012-02-22 05:02:47 +000010025 // Create the return statement that returns the block from the conversion
10026 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010027 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010028 if (Return.isInvalid()) {
10029 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10030 Conv->setInvalidDecl();
10031 return;
10032 }
10033
10034 // Set the body of the conversion function.
10035 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010036 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010037 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010038 Conv->getLocation()));
10039
Douglas Gregored90df32012-02-22 05:02:47 +000010040 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010041 if (ASTMutationListener *L = getASTMutationListener()) {
10042 L->CompletedImplicitDefinition(Conv);
10043 }
10044}
10045
Douglas Gregord2f70072012-03-10 06:53:13 +000010046/// \brief Determine whether the given list arguments contains exactly one
10047/// "real" (non-default) argument.
10048static bool hasOneRealArgument(MultiExprArg Args) {
10049 switch (Args.size()) {
10050 case 0:
10051 return false;
10052
10053 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010054 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010055 return false;
10056
10057 // fall through
10058 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010059 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010060 }
10061
10062 return false;
10063}
10064
John McCalldadc5752010-08-24 06:29:42 +000010065ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010066Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010067 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010068 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010069 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010070 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010071 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010072 unsigned ConstructKind,
10073 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010074 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010075
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010076 // C++0x [class.copy]p34:
10077 // When certain criteria are met, an implementation is allowed to
10078 // omit the copy/move construction of a class object, even if the
10079 // copy/move constructor and/or destructor for the object have
10080 // side effects. [...]
10081 // - when a temporary class object that has not been bound to a
10082 // reference (12.2) would be copied/moved to a class object
10083 // with the same cv-unqualified type, the copy/move operation
10084 // can be omitted by constructing the temporary object
10085 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010086 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010087 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010088 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010089 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010090 }
Mike Stump11289f42009-09-09 15:08:12 +000010091
10092 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010093 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010094 IsListInitialization, RequiresZeroInit,
10095 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010096}
10097
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010098/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10099/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010100ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010101Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10102 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010103 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010104 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010105 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010106 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010107 unsigned ConstructKind,
10108 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010109 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010110 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010111 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010112 HadMultipleCandidates,
10113 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010114 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10115 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010116}
10117
John McCall03c48482010-02-02 09:10:11 +000010118void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010119 if (VD->isInvalidDecl()) return;
10120
John McCall03c48482010-02-02 09:10:11 +000010121 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010122 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010123 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010124 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010125
Chandler Carruth86d17d32011-03-27 21:26:48 +000010126 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010127 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010128 CheckDestructorAccess(VD->getLocation(), Destructor,
10129 PDiag(diag::err_access_dtor_var)
10130 << VD->getDeclName()
10131 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010132 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010133
Chandler Carruth86d17d32011-03-27 21:26:48 +000010134 if (!VD->hasGlobalStorage()) return;
10135
10136 // Emit warning for non-trivial dtor in global scope (a real global,
10137 // class-static, function-static).
10138 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10139
10140 // TODO: this should be re-enabled for static locals by !CXAAtExit
10141 if (!VD->isStaticLocal())
10142 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010143}
10144
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010145/// \brief Given a constructor and the set of arguments provided for the
10146/// constructor, convert the arguments and add any required default arguments
10147/// to form a proper call to this constructor.
10148///
10149/// \returns true if an error occurred, false otherwise.
10150bool
10151Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10152 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010153 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010154 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010155 bool AllowExplicit,
10156 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010157 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10158 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010159 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010160
10161 const FunctionProtoType *Proto
10162 = Constructor->getType()->getAs<FunctionProtoType>();
10163 assert(Proto && "Constructor without a prototype?");
10164 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010165
10166 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010167 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010168 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010169 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010170 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010171
10172 VariadicCallType CallType =
10173 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010174 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010175 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010176 Proto, 0,
10177 llvm::makeArrayRef(Args, NumArgs),
10178 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010179 CallType, AllowExplicit,
10180 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010181 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010182
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010183 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010184
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010185 CheckConstructorCall(Constructor,
10186 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10187 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010188 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010189
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010190 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010191}
10192
Anders Carlssone363c8e2009-12-12 00:32:00 +000010193static inline bool
10194CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10195 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010196 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010197 if (isa<NamespaceDecl>(DC)) {
10198 return SemaRef.Diag(FnDecl->getLocation(),
10199 diag::err_operator_new_delete_declared_in_namespace)
10200 << FnDecl->getDeclName();
10201 }
10202
10203 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010204 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010205 return SemaRef.Diag(FnDecl->getLocation(),
10206 diag::err_operator_new_delete_declared_static)
10207 << FnDecl->getDeclName();
10208 }
10209
Anders Carlsson60659a82009-12-12 02:43:16 +000010210 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010211}
10212
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010213static inline bool
10214CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10215 CanQualType ExpectedResultType,
10216 CanQualType ExpectedFirstParamType,
10217 unsigned DependentParamTypeDiag,
10218 unsigned InvalidParamTypeDiag) {
10219 QualType ResultType =
10220 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10221
10222 // Check that the result type is not dependent.
10223 if (ResultType->isDependentType())
10224 return SemaRef.Diag(FnDecl->getLocation(),
10225 diag::err_operator_new_delete_dependent_result_type)
10226 << FnDecl->getDeclName() << ExpectedResultType;
10227
10228 // Check that the result type is what we expect.
10229 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10230 return SemaRef.Diag(FnDecl->getLocation(),
10231 diag::err_operator_new_delete_invalid_result_type)
10232 << FnDecl->getDeclName() << ExpectedResultType;
10233
10234 // A function template must have at least 2 parameters.
10235 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10236 return SemaRef.Diag(FnDecl->getLocation(),
10237 diag::err_operator_new_delete_template_too_few_parameters)
10238 << FnDecl->getDeclName();
10239
10240 // The function decl must have at least 1 parameter.
10241 if (FnDecl->getNumParams() == 0)
10242 return SemaRef.Diag(FnDecl->getLocation(),
10243 diag::err_operator_new_delete_too_few_parameters)
10244 << FnDecl->getDeclName();
10245
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010246 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010247 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10248 if (FirstParamType->isDependentType())
10249 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10250 << FnDecl->getDeclName() << ExpectedFirstParamType;
10251
10252 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010253 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010254 ExpectedFirstParamType)
10255 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10256 << FnDecl->getDeclName() << ExpectedFirstParamType;
10257
10258 return false;
10259}
10260
Anders Carlsson12308f42009-12-11 23:23:22 +000010261static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010262CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010263 // C++ [basic.stc.dynamic.allocation]p1:
10264 // A program is ill-formed if an allocation function is declared in a
10265 // namespace scope other than global scope or declared static in global
10266 // scope.
10267 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10268 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010269
10270 CanQualType SizeTy =
10271 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10272
10273 // C++ [basic.stc.dynamic.allocation]p1:
10274 // The return type shall be void*. The first parameter shall have type
10275 // std::size_t.
10276 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10277 SizeTy,
10278 diag::err_operator_new_dependent_param_type,
10279 diag::err_operator_new_param_type))
10280 return true;
10281
10282 // C++ [basic.stc.dynamic.allocation]p1:
10283 // The first parameter shall not have an associated default argument.
10284 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010285 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010286 diag::err_operator_new_default_arg)
10287 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10288
10289 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010290}
10291
10292static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010293CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010294 // C++ [basic.stc.dynamic.deallocation]p1:
10295 // A program is ill-formed if deallocation functions are declared in a
10296 // namespace scope other than global scope or declared static in global
10297 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010298 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10299 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010300
10301 // C++ [basic.stc.dynamic.deallocation]p2:
10302 // Each deallocation function shall return void and its first parameter
10303 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010304 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10305 SemaRef.Context.VoidPtrTy,
10306 diag::err_operator_delete_dependent_param_type,
10307 diag::err_operator_delete_param_type))
10308 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010309
Anders Carlsson12308f42009-12-11 23:23:22 +000010310 return false;
10311}
10312
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010313/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10314/// of this overloaded operator is well-formed. If so, returns false;
10315/// otherwise, emits appropriate diagnostics and returns true.
10316bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010317 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010318 "Expected an overloaded operator declaration");
10319
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010320 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10321
Mike Stump11289f42009-09-09 15:08:12 +000010322 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010323 // The allocation and deallocation functions, operator new,
10324 // operator new[], operator delete and operator delete[], are
10325 // described completely in 3.7.3. The attributes and restrictions
10326 // found in the rest of this subclause do not apply to them unless
10327 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010328 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010329 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010330
Anders Carlsson22f443f2009-12-12 00:26:23 +000010331 if (Op == OO_New || Op == OO_Array_New)
10332 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010333
10334 // C++ [over.oper]p6:
10335 // An operator function shall either be a non-static member
10336 // function or be a non-member function and have at least one
10337 // parameter whose type is a class, a reference to a class, an
10338 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010339 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10340 if (MethodDecl->isStatic())
10341 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010342 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010343 } else {
10344 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +000010345 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10346 ParamEnd = FnDecl->param_end();
10347 Param != ParamEnd; ++Param) {
10348 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010349 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10350 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010351 ClassOrEnumParam = true;
10352 break;
10353 }
10354 }
10355
Douglas Gregord69246b2008-11-17 16:14:12 +000010356 if (!ClassOrEnumParam)
10357 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010358 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010359 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010360 }
10361
10362 // C++ [over.oper]p8:
10363 // An operator function cannot have default arguments (8.3.6),
10364 // except where explicitly stated below.
10365 //
Mike Stump11289f42009-09-09 15:08:12 +000010366 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010367 // (C++ [over.call]p1).
10368 if (Op != OO_Call) {
10369 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10370 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010371 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +000010372 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010373 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010374 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010375 }
10376 }
10377
Douglas Gregor6cf08062008-11-10 13:38:07 +000010378 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10379 { false, false, false }
10380#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10381 , { Unary, Binary, MemberOnly }
10382#include "clang/Basic/OperatorKinds.def"
10383 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010384
Douglas Gregor6cf08062008-11-10 13:38:07 +000010385 bool CanBeUnaryOperator = OperatorUses[Op][0];
10386 bool CanBeBinaryOperator = OperatorUses[Op][1];
10387 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010388
10389 // C++ [over.oper]p8:
10390 // [...] Operator functions cannot have more or fewer parameters
10391 // than the number required for the corresponding operator, as
10392 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010393 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010394 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010395 if (Op != OO_Call &&
10396 ((NumParams == 1 && !CanBeUnaryOperator) ||
10397 (NumParams == 2 && !CanBeBinaryOperator) ||
10398 (NumParams < 1) || (NumParams > 2))) {
10399 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010400 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010401 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010402 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010403 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010404 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010405 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010406 assert(CanBeBinaryOperator &&
10407 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010408 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010409 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010410
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010411 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010412 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010413 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010414
Douglas Gregord69246b2008-11-17 16:14:12 +000010415 // Overloaded operators other than operator() cannot be variadic.
10416 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010417 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010418 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010419 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010420 }
10421
10422 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010423 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10424 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010425 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010426 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010427 }
10428
10429 // C++ [over.inc]p1:
10430 // The user-defined function called operator++ implements the
10431 // prefix and postfix ++ operator. If this function is a member
10432 // function with no parameters, or a non-member function with one
10433 // parameter of class or enumeration type, it defines the prefix
10434 // increment operator ++ for objects of that type. If the function
10435 // is a member function with one parameter (which shall be of type
10436 // int) or a non-member function with two parameters (the second
10437 // of which shall be of type int), it defines the postfix
10438 // increment operator ++ for objects of that type.
10439 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10440 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10441 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +000010442 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010443 ParamIsInt = BT->getKind() == BuiltinType::Int;
10444
Chris Lattner2b786902008-11-21 07:50:02 +000010445 if (!ParamIsInt)
10446 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010447 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010448 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010449 }
10450
Douglas Gregord69246b2008-11-17 16:14:12 +000010451 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010452}
Chris Lattner3b024a32008-12-17 07:09:26 +000010453
Alexis Huntc88db062010-01-13 09:01:02 +000010454/// CheckLiteralOperatorDeclaration - Check whether the declaration
10455/// of this literal operator function is well-formed. If so, returns
10456/// false; otherwise, emits appropriate diagnostics and returns true.
10457bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010458 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010459 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10460 << FnDecl->getDeclName();
10461 return true;
10462 }
10463
Richard Smith72eebee2012-03-04 09:41:16 +000010464 if (FnDecl->isExternC()) {
10465 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10466 return true;
10467 }
10468
Alexis Huntc88db062010-01-13 09:01:02 +000010469 bool Valid = false;
10470
Richard Smithbcc22fc2012-03-09 08:00:36 +000010471 // This might be the definition of a literal operator template.
10472 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10473 // This might be a specialization of a literal operator template.
10474 if (!TpDecl)
10475 TpDecl = FnDecl->getPrimaryTemplate();
10476
Alexis Hunt7dd26172010-04-07 23:11:06 +000010477 // template <char...> type operator "" name() is the only valid template
10478 // signature, and the only valid signature with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010479 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010480 if (FnDecl->param_size() == 0) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000010481 // Must have only one template parameter
10482 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10483 if (Params->size() == 1) {
10484 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010485 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010486
Alexis Hunt7dd26172010-04-07 23:11:06 +000010487 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010488 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10489 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10490 Valid = true;
10491 }
10492 }
Richard Smith72eebee2012-03-04 09:41:16 +000010493 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010494 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010495 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10496
Richard Smith72eebee2012-03-04 09:41:16 +000010497 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010498
Alexis Hunt079a6f72010-04-07 22:57:35 +000010499 // unsigned long long int, long double, and any character type are allowed
10500 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010501 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10502 Context.hasSameType(T, Context.LongDoubleTy) ||
10503 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010504 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010505 Context.hasSameType(T, Context.Char16Ty) ||
10506 Context.hasSameType(T, Context.Char32Ty)) {
10507 if (++Param == FnDecl->param_end())
10508 Valid = true;
10509 goto FinishedParams;
10510 }
10511
Alexis Hunt079a6f72010-04-07 22:57:35 +000010512 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010513 const PointerType *PT = T->getAs<PointerType>();
10514 if (!PT)
10515 goto FinishedParams;
10516 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010517 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010518 goto FinishedParams;
10519 T = T.getUnqualifiedType();
10520
10521 // Move on to the second parameter;
10522 ++Param;
10523
10524 // If there is no second parameter, the first must be a const char *
10525 if (Param == FnDecl->param_end()) {
10526 if (Context.hasSameType(T, Context.CharTy))
10527 Valid = true;
10528 goto FinishedParams;
10529 }
10530
10531 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10532 // are allowed as the first parameter to a two-parameter function
10533 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010534 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010535 Context.hasSameType(T, Context.Char16Ty) ||
10536 Context.hasSameType(T, Context.Char32Ty)))
10537 goto FinishedParams;
10538
10539 // The second and final parameter must be an std::size_t
10540 T = (*Param)->getType().getUnqualifiedType();
10541 if (Context.hasSameType(T, Context.getSizeType()) &&
10542 ++Param == FnDecl->param_end())
10543 Valid = true;
10544 }
10545
10546 // FIXME: This diagnostic is absolutely terrible.
10547FinishedParams:
10548 if (!Valid) {
10549 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10550 << FnDecl->getDeclName();
10551 return true;
10552 }
10553
Richard Smith768cecc2012-03-09 08:16:22 +000010554 // A parameter-declaration-clause containing a default argument is not
10555 // equivalent to any of the permitted forms.
10556 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10557 ParamEnd = FnDecl->param_end();
10558 Param != ParamEnd; ++Param) {
10559 if ((*Param)->hasDefaultArg()) {
10560 Diag((*Param)->getDefaultArgRange().getBegin(),
10561 diag::err_literal_operator_default_argument)
10562 << (*Param)->getDefaultArgRange();
10563 break;
10564 }
10565 }
10566
Richard Smith0df56f42012-03-08 02:39:21 +000010567 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010568 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10569 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010570 // C++11 [usrlit.suffix]p1:
10571 // Literal suffix identifiers that do not start with an underscore
10572 // are reserved for future standardization.
10573 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor86325ad2011-08-30 22:40:35 +000010574 }
Richard Smith0df56f42012-03-08 02:39:21 +000010575
Alexis Huntc88db062010-01-13 09:01:02 +000010576 return false;
10577}
10578
Douglas Gregor07665a62009-01-05 19:45:36 +000010579/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10580/// linkage specification, including the language and (if present)
10581/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10582/// the location of the language string literal, which is provided
10583/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10584/// the '{' brace. Otherwise, this linkage specification does not
10585/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000010586Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10587 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010588 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +000010589 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +000010590 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +000010591 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +000010592 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +000010593 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +000010594 Language = LinkageSpecDecl::lang_cxx;
10595 else {
Douglas Gregor07665a62009-01-05 19:45:36 +000010596 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +000010597 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000010598 }
Mike Stump11289f42009-09-09 15:08:12 +000010599
Chris Lattner438e5012008-12-17 07:13:27 +000010600 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000010601
Douglas Gregor07665a62009-01-05 19:45:36 +000010602 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindola327be3c2013-04-26 01:30:23 +000010603 ExternLoc, LangLoc, Language,
10604 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010605 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000010606 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000010607 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000010608}
10609
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000010610/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000010611/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10612/// valid, it's the position of the closing '}' brace in a linkage
10613/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000010614Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010615 Decl *LinkageSpec,
10616 SourceLocation RBraceLoc) {
10617 if (LinkageSpec) {
10618 if (RBraceLoc.isValid()) {
10619 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10620 LSDecl->setRBraceLoc(RBraceLoc);
10621 }
Douglas Gregor07665a62009-01-05 19:45:36 +000010622 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010623 }
Douglas Gregor07665a62009-01-05 19:45:36 +000010624 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000010625}
10626
Michael Han84324352013-02-22 17:15:32 +000010627Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10628 AttributeList *AttrList,
10629 SourceLocation SemiLoc) {
10630 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10631 // Attribute declarations appertain to empty declaration so we handle
10632 // them here.
10633 if (AttrList)
10634 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000010635
Michael Han84324352013-02-22 17:15:32 +000010636 CurContext->addDecl(ED);
10637 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000010638}
10639
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000010640/// \brief Perform semantic analysis for the variable declaration that
10641/// occurs within a C++ catch clause, returning the newly-created
10642/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000010643VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000010644 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010645 SourceLocation StartLoc,
10646 SourceLocation Loc,
10647 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000010648 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000010649 QualType ExDeclType = TInfo->getType();
10650
Sebastian Redl54c04d42008-12-22 19:15:10 +000010651 // Arrays and functions decay.
10652 if (ExDeclType->isArrayType())
10653 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10654 else if (ExDeclType->isFunctionType())
10655 ExDeclType = Context.getPointerType(ExDeclType);
10656
10657 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10658 // The exception-declaration shall not denote a pointer or reference to an
10659 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000010660 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000010661 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000010662 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000010663 Invalid = true;
10664 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000010665
Sebastian Redl54c04d42008-12-22 19:15:10 +000010666 QualType BaseType = ExDeclType;
10667 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000010668 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010669 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000010670 BaseType = Ptr->getPointeeType();
10671 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000010672 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000010673 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000010674 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000010675 BaseType = Ref->getPointeeType();
10676 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000010677 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000010678 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000010679 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000010680 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000010681 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000010682
Mike Stump11289f42009-09-09 15:08:12 +000010683 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000010684 RequireNonAbstractType(Loc, ExDeclType,
10685 diag::err_abstract_type_in_decl,
10686 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000010687 Invalid = true;
10688
John McCall2ca705e2010-07-24 00:37:23 +000010689 // Only the non-fragile NeXT runtime currently supports C++ catches
10690 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010691 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000010692 QualType T = ExDeclType;
10693 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10694 T = RT->getPointeeType();
10695
10696 if (T->isObjCObjectType()) {
10697 Diag(Loc, diag::err_objc_object_catch);
10698 Invalid = true;
10699 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000010700 // FIXME: should this be a test for macosx-fragile specifically?
10701 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000010702 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000010703 }
10704 }
10705
Abramo Bagnaradff19302011-03-08 08:55:46 +000010706 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000010707 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000010708 ExDecl->setExceptionVariable(true);
10709
Douglas Gregor8ca0c642011-12-10 01:22:52 +000010710 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010711 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000010712 Invalid = true;
10713
Douglas Gregor750734c2011-07-06 18:14:43 +000010714 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000010715 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000010716 // Insulate this from anything else we might currently be parsing.
10717 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10718
Douglas Gregor6de584c2010-03-05 23:38:39 +000010719 // C++ [except.handle]p16:
10720 // The object declared in an exception-declaration or, if the
10721 // exception-declaration does not specify a name, a temporary (12.2) is
10722 // copy-initialized (8.5) from the exception object. [...]
10723 // The object is destroyed when the handler exits, after the destruction
10724 // of any automatic objects initialized within the handler.
10725 //
10726 // We just pretend to initialize the object with itself, then make sure
10727 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000010728 QualType initType = ExDeclType;
10729
10730 InitializedEntity entity =
10731 InitializedEntity::InitializeVariable(ExDecl);
10732 InitializationKind initKind =
10733 InitializationKind::CreateCopy(Loc, SourceLocation());
10734
10735 Expr *opaqueValue =
10736 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000010737 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10738 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000010739 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000010740 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000010741 else {
10742 // If the constructor used was non-trivial, set this as the
10743 // "initializer".
10744 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10745 if (!construct->getConstructor()->isTrivial()) {
10746 Expr *init = MaybeCreateExprWithCleanups(construct);
10747 ExDecl->setInit(init);
10748 }
10749
10750 // And make sure it's destructable.
10751 FinalizeVarWithDestructor(ExDecl, recordType);
10752 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000010753 }
10754 }
10755
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000010756 if (Invalid)
10757 ExDecl->setInvalidDecl();
10758
10759 return ExDecl;
10760}
10761
10762/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10763/// handler.
John McCall48871652010-08-21 09:40:31 +000010764Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000010765 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000010766 bool Invalid = D.isInvalidType();
10767
10768 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000010769 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10770 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000010771 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10772 D.getIdentifierLoc());
10773 Invalid = true;
10774 }
10775
Sebastian Redl54c04d42008-12-22 19:15:10 +000010776 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010777 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000010778 LookupOrdinaryName,
10779 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000010780 // The scope should be freshly made just for us. There is just no way
10781 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000010782 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000010783 if (PrevDecl->isTemplateParameter()) {
10784 // Maybe we will complain about the shadowed template parameter.
10785 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000010786 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000010787 }
10788 }
10789
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000010790 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000010791 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10792 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000010793 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000010794 }
10795
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000010796 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010797 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000010798 D.getIdentifierLoc(),
10799 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000010800 if (Invalid)
10801 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010802
Sebastian Redl54c04d42008-12-22 19:15:10 +000010803 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000010804 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000010805 PushOnScopeChains(ExDecl, S);
10806 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010807 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000010808
Douglas Gregor758a8692009-06-17 21:51:59 +000010809 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000010810 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000010811}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000010812
Abramo Bagnaraea947882011-03-08 16:41:52 +000010813Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000010814 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000010815 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000010816 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000010817 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000010818
Richard Smithded9c2e2012-07-11 22:37:56 +000010819 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10820 return 0;
10821
10822 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10823 AssertMessage, RParenLoc, false);
10824}
10825
10826Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10827 Expr *AssertExpr,
10828 StringLiteral *AssertMessage,
10829 SourceLocation RParenLoc,
10830 bool Failed) {
10831 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10832 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010833 // In a static_assert-declaration, the constant-expression shall be a
10834 // constant expression that can be contextually converted to bool.
10835 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10836 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000010837 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000010838
Richard Smith902ca212011-12-14 23:32:26 +000010839 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000010840 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000010841 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000010842 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000010843 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000010844
Richard Smithded9c2e2012-07-11 22:37:56 +000010845 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010846 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000010847 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000010848 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000010849 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000010850 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000010851 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000010852 }
Anders Carlsson54b26982009-03-14 00:33:21 +000010853 }
Mike Stump11289f42009-09-09 15:08:12 +000010854
Abramo Bagnaraea947882011-03-08 16:41:52 +000010855 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000010856 AssertExpr, AssertMessage, RParenLoc,
10857 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000010858
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010859 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000010860 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000010861}
Sebastian Redlf769df52009-03-24 22:27:57 +000010862
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010863/// \brief Perform semantic analysis of the given friend type declaration.
10864///
10865/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000010866FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000010867 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010868 TypeSourceInfo *TSInfo) {
10869 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10870
10871 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000010872 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010873
Richard Smithc8239732011-10-18 21:39:00 +000010874 // C++03 [class.friend]p2:
10875 // An elaborated-type-specifier shall be used in a friend declaration
10876 // for a class.*
10877 //
10878 // * The class-key of the elaborated-type-specifier is required.
10879 if (!ActiveTemplateInstantiations.empty()) {
10880 // Do not complain about the form of friend template types during
10881 // template instantiation; we will already have complained when the
10882 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000010883 } else {
10884 if (!T->isElaboratedTypeSpecifier()) {
10885 // If we evaluated the type to a record type, suggest putting
10886 // a tag in front.
10887 if (const RecordType *RT = T->getAs<RecordType>()) {
10888 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000010889
Nick Lewycky36722d22013-02-06 05:59:33 +000010890 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000010891
Nick Lewycky36722d22013-02-06 05:59:33 +000010892 Diag(TypeRange.getBegin(),
10893 getLangOpts().CPlusPlus11 ?
10894 diag::warn_cxx98_compat_unelaborated_friend_type :
10895 diag::ext_unelaborated_friend_type)
10896 << (unsigned) RD->getTagKind()
10897 << T
10898 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10899 InsertionText);
10900 } else {
10901 Diag(FriendLoc,
10902 getLangOpts().CPlusPlus11 ?
10903 diag::warn_cxx98_compat_nonclass_type_friend :
10904 diag::ext_nonclass_type_friend)
10905 << T
10906 << TypeRange;
10907 }
10908 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000010909 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010910 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000010911 diag::warn_cxx98_compat_enum_friend :
10912 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010913 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000010914 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010915 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010916
Nick Lewycky36722d22013-02-06 05:59:33 +000010917 // C++11 [class.friend]p3:
10918 // A friend declaration that does not declare a function shall have one
10919 // of the following forms:
10920 // friend elaborated-type-specifier ;
10921 // friend simple-type-specifier ;
10922 // friend typename-specifier ;
10923 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10924 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10925 }
Richard Smitha31a89a2012-09-20 01:31:00 +000010926
Douglas Gregor3b4abb62010-04-07 17:57:12 +000010927 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000010928 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000010929 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000010930 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010931}
10932
John McCallace48cd2010-10-19 01:40:49 +000010933/// Handle a friend tag declaration where the scope specifier was
10934/// templated.
10935Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10936 unsigned TagSpec, SourceLocation TagLoc,
10937 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000010938 IdentifierInfo *Name,
10939 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000010940 AttributeList *Attr,
10941 MultiTemplateParamsArg TempParamLists) {
10942 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10943
10944 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000010945 bool Invalid = false;
10946
10947 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +000010948 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010949 TempParamLists.data(),
John McCallace48cd2010-10-19 01:40:49 +000010950 TempParamLists.size(),
10951 /*friend*/ true,
10952 isExplicitSpecialization,
10953 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000010954 if (TemplateParams->size() > 0) {
10955 // This is a declaration of a class template.
10956 if (Invalid)
10957 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010958
Eric Christopher6f228b52011-07-21 05:34:24 +000010959 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10960 SS, Name, NameLoc, Attr,
10961 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000010962 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000010963 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010964 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000010965 } else {
10966 // The "template<>" header is extraneous.
10967 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10968 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10969 isExplicitSpecialization = true;
10970 }
10971 }
10972
10973 if (Invalid) return 0;
10974
John McCallace48cd2010-10-19 01:40:49 +000010975 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000010976 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010977 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000010978 isAllExplicitSpecializations = false;
10979 break;
10980 }
10981 }
10982
10983 // FIXME: don't ignore attributes.
10984
10985 // If it's explicit specializations all the way down, just forget
10986 // about the template header and build an appropriate non-templated
10987 // friend. TODO: for source fidelity, remember the headers.
10988 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010989 if (SS.isEmpty()) {
10990 bool Owned = false;
10991 bool IsDependent = false;
10992 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10993 Attr, AS_public,
10994 /*ModulePrivateLoc=*/SourceLocation(),
10995 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010996 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010997 /*ScopedEnumUsesClassTag=*/false,
10998 /*UnderlyingType=*/TypeResult());
10999 }
11000
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011001 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011002 ElaboratedTypeKeyword Keyword
11003 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011004 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011005 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011006 if (T.isNull())
11007 return 0;
11008
11009 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11010 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011011 DependentNameTypeLoc TL =
11012 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011013 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011014 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011015 TL.setNameLoc(NameLoc);
11016 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011017 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011018 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011019 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011020 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011021 }
11022
11023 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011024 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011025 Friend->setAccess(AS_public);
11026 CurContext->addDecl(Friend);
11027 return Friend;
11028 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011029
11030 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11031
11032
John McCallace48cd2010-10-19 01:40:49 +000011033
11034 // Handle the case of a templated-scope friend class. e.g.
11035 // template <class T> class A<T>::B;
11036 // FIXME: we don't support these right now.
11037 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11038 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11039 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011040 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011041 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011042 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011043 TL.setNameLoc(NameLoc);
11044
11045 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011046 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011047 Friend->setAccess(AS_public);
11048 Friend->setUnsupportedFriend(true);
11049 CurContext->addDecl(Friend);
11050 return Friend;
11051}
11052
11053
John McCall11083da2009-09-16 22:47:08 +000011054/// Handle a friend type declaration. This works in tandem with
11055/// ActOnTag.
11056///
11057/// Notes on friend class templates:
11058///
11059/// We generally treat friend class declarations as if they were
11060/// declaring a class. So, for example, the elaborated type specifier
11061/// in a friend declaration is required to obey the restrictions of a
11062/// class-head (i.e. no typedefs in the scope chain), template
11063/// parameters are required to match up with simple template-ids, &c.
11064/// However, unlike when declaring a template specialization, it's
11065/// okay to refer to a template specialization without an empty
11066/// template parameter declaration, e.g.
11067/// friend class A<T>::B<unsigned>;
11068/// We permit this as a special case; if there are any template
11069/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011070/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011071Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011072 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011073 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011074
11075 assert(DS.isFriendSpecified());
11076 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11077
John McCall11083da2009-09-16 22:47:08 +000011078 // Try to convert the decl specifier to a type. This works for
11079 // friend templates because ActOnTag never produces a ClassTemplateDecl
11080 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011081 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011082 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11083 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011084 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011085 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011086
Douglas Gregor6c110f32010-12-16 01:14:37 +000011087 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11088 return 0;
11089
John McCall11083da2009-09-16 22:47:08 +000011090 // This is definitely an error in C++98. It's probably meant to
11091 // be forbidden in C++0x, too, but the specification is just
11092 // poorly written.
11093 //
11094 // The problem is with declarations like the following:
11095 // template <T> friend A<T>::foo;
11096 // where deciding whether a class C is a friend or not now hinges
11097 // on whether there exists an instantiation of A that causes
11098 // 'foo' to equal C. There are restrictions on class-heads
11099 // (which we declare (by fiat) elaborated friend declarations to
11100 // be) that makes this tractable.
11101 //
11102 // FIXME: handle "template <> friend class A<T>;", which
11103 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011104 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011105 Diag(Loc, diag::err_tagless_friend_type_template)
11106 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011107 return 0;
John McCall11083da2009-09-16 22:47:08 +000011108 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011109
John McCallaa74a0c2009-08-28 07:59:38 +000011110 // C++98 [class.friend]p1: A friend of a class is a function
11111 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011112 // This is fixed in DR77, which just barely didn't make the C++03
11113 // deadline. It's also a very silly restriction that seriously
11114 // affects inner classes and which nobody else seems to implement;
11115 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011116 //
11117 // But note that we could warn about it: it's always useless to
11118 // friend one of your own members (it's not, however, worthless to
11119 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011120
John McCall11083da2009-09-16 22:47:08 +000011121 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011122 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011123 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011124 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011125 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011126 TSI,
John McCall11083da2009-09-16 22:47:08 +000011127 DS.getFriendSpecLoc());
11128 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011129 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011130
11131 if (!D)
John McCall48871652010-08-21 09:40:31 +000011132 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011133
John McCall11083da2009-09-16 22:47:08 +000011134 D->setAccess(AS_public);
11135 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011136
John McCall48871652010-08-21 09:40:31 +000011137 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011138}
11139
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011140NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11141 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011142 const DeclSpec &DS = D.getDeclSpec();
11143
11144 assert(DS.isFriendSpecified());
11145 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11146
11147 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011148 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011149
11150 // C++ [class.friend]p1
11151 // A friend of a class is a function or class....
11152 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011153 // It *doesn't* see through dependent types, which is correct
11154 // according to [temp.arg.type]p3:
11155 // If a declaration acquires a function type through a
11156 // type dependent on a template-parameter and this causes
11157 // a declaration that does not use the syntactic form of a
11158 // function declarator to have a function type, the program
11159 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011160 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011161 Diag(Loc, diag::err_unexpected_friend);
11162
11163 // It might be worthwhile to try to recover by creating an
11164 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011165 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011166 }
11167
11168 // C++ [namespace.memdef]p3
11169 // - If a friend declaration in a non-local class first declares a
11170 // class or function, the friend class or function is a member
11171 // of the innermost enclosing namespace.
11172 // - The name of the friend is not found by simple name lookup
11173 // until a matching declaration is provided in that namespace
11174 // scope (either before or after the class declaration granting
11175 // friendship).
11176 // - If a friend function is called, its name may be found by the
11177 // name lookup that considers functions from namespaces and
11178 // classes associated with the types of the function arguments.
11179 // - When looking for a prior declaration of a class or a function
11180 // declared as a friend, scopes outside the innermost enclosing
11181 // namespace scope are not considered.
11182
John McCallde3fd222010-10-12 23:13:28 +000011183 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011184 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11185 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011186 assert(Name);
11187
Douglas Gregor6c110f32010-12-16 01:14:37 +000011188 // Check for unexpanded parameter packs.
11189 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11190 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11191 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11192 return 0;
11193
John McCall07e91c02009-08-06 02:15:43 +000011194 // The context we found the declaration in, or in which we should
11195 // create the declaration.
11196 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011197 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011198 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011199 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011200
John McCallde3fd222010-10-12 23:13:28 +000011201 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +000011202
John McCallde3fd222010-10-12 23:13:28 +000011203 // There are four cases here.
11204 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +000011205 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +000011206 // there as appropriate.
11207 // Recover from invalid scope qualifiers as if they just weren't there.
11208 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +000011209 // C++0x [namespace.memdef]p3:
11210 // If the name in a friend declaration is neither qualified nor
11211 // a template-id and the declaration is a function or an
11212 // elaborated-type-specifier, the lookup to determine whether
11213 // the entity has been previously declared shall not consider
11214 // any scopes outside the innermost enclosing namespace.
11215 // C++0x [class.friend]p11:
11216 // If a friend declaration appears in a local class and the name
11217 // specified is an unqualified name, a prior declaration is
11218 // looked up without considering scopes that are outside the
11219 // innermost enclosing non-class scope. For a friend function
11220 // declaration, if there is no prior declaration, the program is
11221 // ill-formed.
11222 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +000011223 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011224
John McCallf7cfb222010-10-13 05:45:15 +000011225 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011226 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011227
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011228 // Skip class contexts. If someone can cite chapter and verse
11229 // for this behavior, that would be nice --- it's what GCC and
11230 // EDG do, and it seems like a reasonable intent, but the spec
11231 // really only says that checks for unqualified existing
11232 // declarations should stop at the nearest enclosing namespace,
11233 // not that they should only consider the nearest enclosing
11234 // namespace.
11235 while (DC->isRecord())
11236 DC = DC->getParent();
11237
11238 DeclContext *LookupDC = DC;
11239 while (LookupDC->isTransparentContext())
11240 LookupDC = LookupDC->getParent();
11241
11242 while (true) {
11243 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011244
11245 // TODO: decide what we think about using declarations.
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011246 if (isLocal)
John McCall07e91c02009-08-06 02:15:43 +000011247 break;
John McCallf7cfb222010-10-13 05:45:15 +000011248
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011249 if (!Previous.empty()) {
11250 DC = LookupDC;
11251 break;
John McCallf4776592010-10-14 22:22:28 +000011252 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011253
11254 if (isTemplateId) {
11255 if (isa<TranslationUnitDecl>(LookupDC)) break;
11256 } else {
11257 if (LookupDC->isFileContext()) break;
11258 }
11259 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011260 }
11261
John McCallccbc0322010-10-13 06:22:15 +000011262 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregordd847ba2011-11-03 16:37:14 +000011263
Douglas Gregor16e65612011-10-10 01:11:59 +000011264 // C++ [class.friend]p6:
11265 // A function can be defined in a friend declaration of a class if and
11266 // only if the class is a non-local class (9.8), the function name is
11267 // unqualified, and the function has namespace scope.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011268 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011269 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11270 }
11271
John McCallde3fd222010-10-12 23:13:28 +000011272 // - There's a non-dependent scope specifier, in which case we
11273 // compute it and do a previous lookup there for a function
11274 // or function template.
11275 } else if (!SS.getScopeRep()->isDependent()) {
11276 DC = computeDeclContext(SS);
11277 if (!DC) return 0;
11278
11279 if (RequireCompleteDeclContext(SS, DC)) return 0;
11280
11281 LookupQualifiedName(Previous, DC);
11282
11283 // Ignore things found implicitly in the wrong scope.
11284 // TODO: better diagnostics for this case. Suggesting the right
11285 // qualified scope would be nice...
11286 LookupResult::Filter F = Previous.makeFilter();
11287 while (F.hasNext()) {
11288 NamedDecl *D = F.next();
11289 if (!DC->InEnclosingNamespaceSetOf(
11290 D->getDeclContext()->getRedeclContext()))
11291 F.erase();
11292 }
11293 F.done();
11294
11295 if (Previous.empty()) {
11296 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011297 Diag(Loc, diag::err_qualified_friend_not_found)
11298 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011299 return 0;
11300 }
11301
11302 // C++ [class.friend]p1: A friend of a class is a function or
11303 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011304 if (DC->Equals(CurContext))
11305 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011306 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011307 diag::warn_cxx98_compat_friend_is_member :
11308 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011309
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011310 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011311 // C++ [class.friend]p6:
11312 // A function can be defined in a friend declaration of a class if and
11313 // only if the class is a non-local class (9.8), the function name is
11314 // unqualified, and the function has namespace scope.
11315 SemaDiagnosticBuilder DB
11316 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11317
11318 DB << SS.getScopeRep();
11319 if (DC->isFileContext())
11320 DB << FixItHint::CreateRemoval(SS.getRange());
11321 SS.clear();
11322 }
John McCallde3fd222010-10-12 23:13:28 +000011323
11324 // - There's a scope specifier that does not match any template
11325 // parameter lists, in which case we use some arbitrary context,
11326 // create a method or method template, and wait for instantiation.
11327 // - There's a scope specifier that does match some template
11328 // parameter lists, which we don't handle right now.
11329 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011330 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011331 // C++ [class.friend]p6:
11332 // A function can be defined in a friend declaration of a class if and
11333 // only if the class is a non-local class (9.8), the function name is
11334 // unqualified, and the function has namespace scope.
11335 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11336 << SS.getScopeRep();
11337 }
11338
John McCallde3fd222010-10-12 23:13:28 +000011339 DC = CurContext;
11340 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011341 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011342
John McCallf7cfb222010-10-13 05:45:15 +000011343 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011344 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011345 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11346 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11347 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011348 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011349 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11350 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011351 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011352 }
John McCall07e91c02009-08-06 02:15:43 +000011353 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011354
Douglas Gregordd847ba2011-11-03 16:37:14 +000011355 // FIXME: This is an egregious hack to cope with cases where the scope stack
11356 // does not contain the declaration context, i.e., in an out-of-line
11357 // definition of a class.
11358 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11359 if (!DCScope) {
11360 FakeDCScope.setEntity(DC);
11361 DCScope = &FakeDCScope;
11362 }
11363
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011364 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011365 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011366 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011367 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011368
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011369 assert(ND->getDeclContext() == DC);
11370 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011371
John McCall759e32b2009-08-31 22:39:49 +000011372 // Add the function declaration to the appropriate lookup tables,
11373 // adjusting the redeclarations list as necessary. We don't
11374 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011375 //
John McCall759e32b2009-08-31 22:39:49 +000011376 // Also update the scope-based lookup if the target context's
11377 // lookup context is in lexical scope.
11378 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011379 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011380 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011381 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011382 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011383 }
John McCallaa74a0c2009-08-28 07:59:38 +000011384
11385 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011386 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011387 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011388 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011389 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011390
John McCalla0a96892012-08-10 03:15:35 +000011391 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011392 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011393 } else {
11394 if (DC->isRecord()) CheckFriendAccess(ND);
11395
John McCall2c2eb122010-10-16 06:59:13 +000011396 FunctionDecl *FD;
11397 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11398 FD = FTD->getTemplatedDecl();
11399 else
11400 FD = cast<FunctionDecl>(ND);
11401
David Majnemer502b0ed2013-06-25 23:09:30 +000011402 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11403 // default argument expression, that declaration shall be a definition
11404 // and shall be the only declaration of the function or function
11405 // template in the translation unit.
11406 if (functionDeclHasDefaultArgument(FD)) {
11407 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11408 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11409 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11410 } else if (!D.isFunctionDefinition())
11411 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11412 }
11413
John McCall2c2eb122010-10-16 06:59:13 +000011414 // Mark templated-scope function declarations as unsupported.
11415 if (FD->getNumTemplateParameterLists())
11416 FrD->setUnsupportedFriend(true);
11417 }
John McCallde3fd222010-10-12 23:13:28 +000011418
John McCall48871652010-08-21 09:40:31 +000011419 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011420}
11421
John McCall48871652010-08-21 09:40:31 +000011422void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11423 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011424
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011425 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011426 if (!Fn) {
11427 Diag(DelLoc, diag::err_deleted_non_function);
11428 return;
11429 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011430
Douglas Gregorec9fd132012-01-14 16:38:05 +000011431 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011432 // Don't consider the implicit declaration we generate for explicit
11433 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikieaf031a92012-06-29 18:00:25 +000011434 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11435 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011436 Diag(DelLoc, diag::err_deleted_decl_not_first);
11437 Diag(Prev->getLocation(), diag::note_previous_declaration);
11438 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011439 // If the declaration wasn't the first, we delete the function anyway for
11440 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011441 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011442 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011443
11444 if (Fn->isDeleted())
11445 return;
11446
11447 // See if we're deleting a function which is already known to override a
11448 // non-deleted virtual function.
11449 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11450 bool IssuedDiagnostic = false;
11451 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11452 E = MD->end_overridden_methods();
11453 I != E; ++I) {
11454 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11455 if (!IssuedDiagnostic) {
11456 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11457 IssuedDiagnostic = true;
11458 }
11459 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11460 }
11461 }
11462 }
11463
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011464 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011465}
Sebastian Redl4c018662009-04-27 21:33:24 +000011466
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011467void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011468 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011469
11470 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011471 if (MD->getParent()->isDependentType()) {
11472 MD->setDefaulted();
11473 MD->setExplicitlyDefaulted();
11474 return;
11475 }
11476
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011477 CXXSpecialMember Member = getSpecialMember(MD);
11478 if (Member == CXXInvalid) {
11479 Diag(DefaultLoc, diag::err_default_special_members);
11480 return;
11481 }
11482
11483 MD->setDefaulted();
11484 MD->setExplicitlyDefaulted();
11485
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011486 // If this definition appears within the record, do the checking when
11487 // the record is complete.
11488 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011489 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011490 // Find the uninstantiated declaration that actually had the '= default'
11491 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011492 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011493
Richard Smith3901dfe2013-03-27 00:22:47 +000011494 // If the method was defaulted on its first declaration, we will have
11495 // already performed the checking in CheckCompletedCXXClass. Such a
11496 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011497 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011498 return;
11499
Richard Smithd3b5c9082012-07-27 04:22:15 +000011500 CheckExplicitlyDefaultedSpecialMember(MD);
11501
Richard Smithbd305122012-12-11 01:14:52 +000011502 // The exception specification is needed because we are defining the
11503 // function.
11504 ResolveExceptionSpec(DefaultLoc,
11505 MD->getType()->castAs<FunctionProtoType>());
11506
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011507 switch (Member) {
11508 case CXXDefaultConstructor: {
11509 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Alexis Hunt913820d2011-05-13 06:10:58 +000011510 if (!CD->isInvalidDecl())
11511 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11512 break;
11513 }
11514
11515 case CXXCopyConstructor: {
11516 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Alexis Hunt913820d2011-05-13 06:10:58 +000011517 if (!CD->isInvalidDecl())
11518 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011519 break;
11520 }
Alexis Huntf91729462011-05-12 22:46:25 +000011521
Alexis Huntc9a55732011-05-14 05:23:28 +000011522 case CXXCopyAssignment: {
Alexis Huntc9a55732011-05-14 05:23:28 +000011523 if (!MD->isInvalidDecl())
11524 DefineImplicitCopyAssignment(DefaultLoc, MD);
11525 break;
11526 }
11527
Alexis Huntf91729462011-05-12 22:46:25 +000011528 case CXXDestructor: {
11529 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Alexis Hunt913820d2011-05-13 06:10:58 +000011530 if (!DD->isInvalidDecl())
11531 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000011532 break;
11533 }
11534
Sebastian Redl22653ba2011-08-30 19:58:05 +000011535 case CXXMoveConstructor: {
11536 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011537 if (!CD->isInvalidDecl())
11538 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000011539 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011540 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000011541
Sebastian Redl22653ba2011-08-30 19:58:05 +000011542 case CXXMoveAssignment: {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011543 if (!MD->isInvalidDecl())
11544 DefineImplicitMoveAssignment(DefaultLoc, MD);
11545 break;
11546 }
11547
11548 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011549 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011550 }
11551 } else {
11552 Diag(DefaultLoc, diag::err_default_special_members);
11553 }
11554}
11555
Sebastian Redl4c018662009-04-27 21:33:24 +000011556static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000011557 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000011558 Stmt *SubStmt = *CI;
11559 if (!SubStmt)
11560 continue;
11561 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011562 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000011563 diag::err_return_in_constructor_handler);
11564 if (!isa<Expr>(SubStmt))
11565 SearchForReturnInStmt(Self, SubStmt);
11566 }
11567}
11568
11569void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11570 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11571 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11572 SearchForReturnInStmt(*this, Handler);
11573 }
11574}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011575
David Blaikie68f71a32013-01-18 23:03:15 +000011576bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000011577 const CXXMethodDecl *Old) {
11578 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11579 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11580
11581 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11582
11583 // If the calling conventions match, everything is fine
11584 if (NewCC == OldCC)
11585 return false;
11586
11587 // If either of the calling conventions are set to "default", we need to pick
11588 // something more sensible based on the target. This supports code where the
11589 // one method explicitly sets thiscall, and another has no explicit calling
11590 // convention.
11591 CallingConv Default =
11592 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11593 if (NewCC == CC_Default)
11594 NewCC = Default;
11595 if (OldCC == CC_Default)
11596 OldCC = Default;
11597
11598 // If the calling conventions still don't match, then report the error
11599 if (NewCC != OldCC) {
David Blaikie68f71a32013-01-18 23:03:15 +000011600 Diag(New->getLocation(),
11601 diag::err_conflicting_overriding_cc_attributes)
11602 << New->getDeclName() << New->getType() << Old->getType();
11603 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11604 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000011605 }
11606
11607 return false;
11608}
11609
Mike Stump11289f42009-09-09 15:08:12 +000011610bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011611 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000011612 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11613 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011614
Chandler Carruth284bb2e2010-02-15 11:53:20 +000011615 if (Context.hasSameType(NewTy, OldTy) ||
11616 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011617 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011618
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011619 // Check if the return types are covariant
11620 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000011621
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011622 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011623 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11624 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011625 NewClassTy = NewPT->getPointeeType();
11626 OldClassTy = OldPT->getPointeeType();
11627 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011628 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11629 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11630 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11631 NewClassTy = NewRT->getPointeeType();
11632 OldClassTy = OldRT->getPointeeType();
11633 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011634 }
11635 }
Mike Stump11289f42009-09-09 15:08:12 +000011636
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011637 // The return types aren't either both pointers or references to a class type.
11638 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000011639 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011640 diag::err_different_return_type_for_overriding_virtual_function)
11641 << New->getDeclName() << NewTy << OldTy;
11642 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000011643
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011644 return true;
11645 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011646
Anders Carlssone60365b2009-12-31 18:34:24 +000011647 // C++ [class.virtual]p6:
11648 // If the return type of D::f differs from the return type of B::f, the
11649 // class type in the return type of D::f shall be complete at the point of
11650 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000011651 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11652 if (!RT->isBeingDefined() &&
11653 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011654 diag::err_covariant_return_incomplete,
11655 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000011656 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000011657 }
Anders Carlssone60365b2009-12-31 18:34:24 +000011658
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000011659 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011660 // Check if the new class derives from the old class.
11661 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11662 Diag(New->getLocation(),
11663 diag::err_covariant_return_not_derived)
11664 << New->getDeclName() << NewTy << OldTy;
11665 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11666 return true;
11667 }
Mike Stump11289f42009-09-09 15:08:12 +000011668
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011669 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000011670 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000011671 diag::err_covariant_return_inaccessible_base,
11672 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11673 // FIXME: Should this point to the return type?
11674 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000011675 // FIXME: this note won't trigger for delayed access control
11676 // diagnostics, and it's impossible to get an undelayed error
11677 // here from access control during the original parse because
11678 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011679 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11680 return true;
11681 }
11682 }
Mike Stump11289f42009-09-09 15:08:12 +000011683
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011684 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011685 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011686 Diag(New->getLocation(),
11687 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011688 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011689 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11690 return true;
11691 };
Mike Stump11289f42009-09-09 15:08:12 +000011692
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011693
11694 // The new class type must have the same or less qualifiers as the old type.
11695 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11696 Diag(New->getLocation(),
11697 diag::err_covariant_return_type_class_type_more_qualified)
11698 << New->getDeclName() << NewTy << OldTy;
11699 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11700 return true;
11701 };
Mike Stump11289f42009-09-09 15:08:12 +000011702
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011703 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011704}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011705
Douglas Gregor21920e372009-12-01 17:24:26 +000011706/// \brief Mark the given method pure.
11707///
11708/// \param Method the method to be marked pure.
11709///
11710/// \param InitRange the source range that covers the "0" initializer.
11711bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000011712 SourceLocation EndLoc = InitRange.getEnd();
11713 if (EndLoc.isValid())
11714 Method->setRangeEnd(EndLoc);
11715
Douglas Gregor21920e372009-12-01 17:24:26 +000011716 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11717 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000011718 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000011719 }
Douglas Gregor21920e372009-12-01 17:24:26 +000011720
11721 if (!Method->isInvalidDecl())
11722 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11723 << Method->getDeclName() << InitRange;
11724 return true;
11725}
11726
Douglas Gregor926410d2012-02-21 02:22:07 +000011727/// \brief Determine whether the given declaration is a static data member.
11728static bool isStaticDataMember(Decl *D) {
11729 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11730 if (!Var)
11731 return false;
11732
11733 return Var->isStaticDataMember();
11734}
John McCall1f4ee7b2009-12-19 09:28:58 +000011735/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11736/// an initializer for the out-of-line declaration 'Dcl'. The scope
11737/// is a fresh scope pushed for just this purpose.
11738///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011739/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11740/// static data member of class X, names should be looked up in the scope of
11741/// class X.
John McCall48871652010-08-21 09:40:31 +000011742void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011743 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000011744 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011745
John McCall1f4ee7b2009-12-19 09:28:58 +000011746 // We should only get called for declarations with scope specifiers, like:
11747 // int foo::bar;
11748 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000011749 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor926410d2012-02-21 02:22:07 +000011750
11751 // If we are parsing the initializer for a static data member, push a
11752 // new expression evaluation context that is associated with this static
11753 // data member.
11754 if (isStaticDataMember(D))
11755 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011756}
11757
11758/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000011759/// initializer for the out-of-line declaration 'D'.
11760void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011761 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000011762 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011763
Douglas Gregor926410d2012-02-21 02:22:07 +000011764 if (isStaticDataMember(D))
11765 PopExpressionEvaluationContext();
11766
John McCall1f4ee7b2009-12-19 09:28:58 +000011767 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000011768 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000011769}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000011770
11771/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11772/// C++ if/switch/while/for statement.
11773/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000011774DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000011775 // C++ 6.4p2:
11776 // The declarator shall not specify a function or an array.
11777 // The type-specifier-seq shall not contain typedef and shall not declare a
11778 // new class or enumeration.
11779 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11780 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000011781
11782 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000011783 if (!Dcl)
11784 return true;
11785
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000011786 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11787 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000011788 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000011789 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000011790 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000011791
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000011792 return Dcl;
11793}
Anders Carlssonf98849e2009-12-02 17:15:43 +000011794
Douglas Gregor4daf6a32011-07-28 19:11:31 +000011795void Sema::LoadExternalVTableUses() {
11796 if (!ExternalSource)
11797 return;
11798
11799 SmallVector<ExternalVTableUse, 4> VTables;
11800 ExternalSource->ReadUsedVTables(VTables);
11801 SmallVector<VTableUse, 4> NewUses;
11802 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11803 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11804 = VTablesUsed.find(VTables[I].Record);
11805 // Even if a definition wasn't required before, it may be required now.
11806 if (Pos != VTablesUsed.end()) {
11807 if (!Pos->second && VTables[I].DefinitionRequired)
11808 Pos->second = true;
11809 continue;
11810 }
11811
11812 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11813 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11814 }
11815
11816 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11817}
11818
Douglas Gregor88d292c2010-05-13 16:44:06 +000011819void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11820 bool DefinitionRequired) {
11821 // Ignore any vtable uses in unevaluated operands or for classes that do
11822 // not have a vtable.
11823 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000011824 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000011825 return;
11826
Douglas Gregor88d292c2010-05-13 16:44:06 +000011827 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000011828 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000011829 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11830 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11831 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11832 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000011833 // If we already had an entry, check to see if we are promoting this vtable
11834 // to required a definition. If so, we need to reappend to the VTableUses
11835 // list, since we may have already processed the first entry.
11836 if (DefinitionRequired && !Pos.first->second) {
11837 Pos.first->second = true;
11838 } else {
11839 // Otherwise, we can early exit.
11840 return;
11841 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000011842 }
11843
11844 // Local classes need to have their virtual members marked
11845 // immediately. For all other classes, we mark their virtual members
11846 // at the end of the translation unit.
11847 if (Class->isLocalClass())
11848 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000011849 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000011850 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000011851}
11852
Douglas Gregor88d292c2010-05-13 16:44:06 +000011853bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000011854 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000011855 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000011856 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000011857
Douglas Gregor88d292c2010-05-13 16:44:06 +000011858 // Note: The VTableUses vector could grow as a result of marking
11859 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000011860 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000011861 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000011862 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000011863 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000011864 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000011865 if (!Class)
11866 continue;
11867
11868 SourceLocation Loc = VTableUses[I].second;
11869
Richard Smithd3b5c9082012-07-27 04:22:15 +000011870 bool DefineVTable = true;
11871
Douglas Gregor88d292c2010-05-13 16:44:06 +000011872 // If this class has a key function, but that key function is
11873 // defined in another translation unit, we don't need to emit the
11874 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000011875 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000011876 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000011877 switch (KeyFunction->getTemplateSpecializationKind()) {
11878 case TSK_Undeclared:
11879 case TSK_ExplicitSpecialization:
11880 case TSK_ExplicitInstantiationDeclaration:
11881 // The key function is in another translation unit.
Richard Smithd3b5c9082012-07-27 04:22:15 +000011882 DefineVTable = false;
11883 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +000011884
11885 case TSK_ExplicitInstantiationDefinition:
11886 case TSK_ImplicitInstantiation:
11887 // We will be instantiating the key function.
11888 break;
11889 }
11890 } else if (!KeyFunction) {
11891 // If we have a class with no key function that is the subject
11892 // of an explicit instantiation declaration, suppress the
11893 // vtable; it will live with the explicit instantiation
11894 // definition.
11895 bool IsExplicitInstantiationDeclaration
11896 = Class->getTemplateSpecializationKind()
11897 == TSK_ExplicitInstantiationDeclaration;
11898 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11899 REnd = Class->redecls_end();
11900 R != REnd; ++R) {
11901 TemplateSpecializationKind TSK
11902 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11903 if (TSK == TSK_ExplicitInstantiationDeclaration)
11904 IsExplicitInstantiationDeclaration = true;
11905 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11906 IsExplicitInstantiationDeclaration = false;
11907 break;
11908 }
11909 }
11910
11911 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000011912 DefineVTable = false;
11913 }
11914
11915 // The exception specifications for all virtual members may be needed even
11916 // if we are not providing an authoritative form of the vtable in this TU.
11917 // We may choose to emit it available_externally anyway.
11918 if (!DefineVTable) {
11919 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11920 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000011921 }
11922
11923 // Mark all of the virtual members of this class as referenced, so
11924 // that we can build a vtable. Then, tell the AST consumer that a
11925 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000011926 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000011927 MarkVirtualMembersReferenced(Loc, Class);
11928 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11929 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11930
11931 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000011932 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000011933 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000011934 const FunctionDecl *KeyFunctionDef = 0;
11935 if (!KeyFunction ||
11936 (KeyFunction->hasBody(KeyFunctionDef) &&
11937 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000011938 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11939 TSK_ExplicitInstantiationDefinition
11940 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11941 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000011942 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000011943 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000011944 VTableUses.clear();
11945
Douglas Gregor97509692011-04-22 22:25:37 +000011946 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000011947}
Anders Carlsson82fccd02009-12-07 08:24:59 +000011948
Richard Smithd3b5c9082012-07-27 04:22:15 +000011949void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11950 const CXXRecordDecl *RD) {
11951 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11952 E = RD->method_end(); I != E; ++I)
11953 if ((*I)->isVirtual() && !(*I)->isPure())
11954 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11955}
11956
Rafael Espindola5b334082010-03-26 00:36:59 +000011957void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11958 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000011959 // Mark all functions which will appear in RD's vtable as used.
11960 CXXFinalOverriderMap FinalOverriders;
11961 RD->getFinalOverriders(FinalOverriders);
11962 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11963 E = FinalOverriders.end();
11964 I != E; ++I) {
11965 for (OverridingMethods::const_iterator OI = I->second.begin(),
11966 OE = I->second.end();
11967 OI != OE; ++OI) {
11968 assert(OI->second.size() > 0 && "no final overrider");
11969 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000011970
Richard Smith4ff9ff92012-07-07 06:59:51 +000011971 // C++ [basic.def.odr]p2:
11972 // [...] A virtual member function is used if it is not pure. [...]
11973 if (!Overrider->isPure())
11974 MarkFunctionReferenced(Loc, Overrider);
11975 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000011976 }
Rafael Espindola5b334082010-03-26 00:36:59 +000011977
11978 // Only classes that have virtual bases need a VTT.
11979 if (RD->getNumVBases() == 0)
11980 return;
11981
11982 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11983 e = RD->bases_end(); i != e; ++i) {
11984 const CXXRecordDecl *Base =
11985 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000011986 if (Base->getNumVBases() == 0)
11987 continue;
11988 MarkVirtualMembersReferenced(Loc, Base);
11989 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000011990}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000011991
11992/// SetIvarInitializers - This routine builds initialization ASTs for the
11993/// Objective-C implementation whose ivars need be initialized.
11994void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011995 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000011996 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000011997 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011998 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000011999 CollectIvarsToConstructOrDestruct(OID, ivars);
12000 if (ivars.empty())
12001 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012002 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012003 for (unsigned i = 0; i < ivars.size(); i++) {
12004 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012005 if (Field->isInvalidDecl())
12006 continue;
12007
Alexis Hunt1d792652011-01-08 20:30:50 +000012008 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012009 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12010 InitializationKind InitKind =
12011 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012012
12013 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12014 ExprResult MemberInit =
12015 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012016 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012017 // Note, MemberInit could actually come back empty if no initialization
12018 // is required (e.g., because it would call a trivial default constructor)
12019 if (!MemberInit.get() || MemberInit.isInvalid())
12020 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012021
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012022 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012023 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12024 SourceLocation(),
12025 MemberInit.takeAs<Expr>(),
12026 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012027 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012028
12029 // Be sure that the destructor is accessible and is marked as referenced.
12030 if (const RecordType *RecordTy
12031 = Context.getBaseElementType(Field->getType())
12032 ->getAs<RecordType>()) {
12033 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012034 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012035 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012036 CheckDestructorAccess(Field->getLocation(), Destructor,
12037 PDiag(diag::err_access_dtor_ivar)
12038 << Context.getBaseElementType(Field->getType()));
12039 }
12040 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012041 }
12042 ObjCImplementation->setIvarInitializers(Context,
12043 AllToInit.data(), AllToInit.size());
12044 }
12045}
Alexis Hunt6118d662011-05-04 05:57:24 +000012046
Alexis Hunt27a761d2011-05-04 23:29:54 +000012047static
12048void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12049 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12050 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12051 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12052 Sema &S) {
12053 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12054 CE = Current.end();
12055 if (Ctor->isInvalidDecl())
12056 return;
12057
Richard Smith802c4b72012-08-23 06:16:52 +000012058 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12059
12060 // Target may not be determinable yet, for instance if this is a dependent
12061 // call in an uninstantiated template.
12062 if (Target) {
12063 const FunctionDecl *FNTarget = 0;
12064 (void)Target->hasBody(FNTarget);
12065 Target = const_cast<CXXConstructorDecl*>(
12066 cast_or_null<CXXConstructorDecl>(FNTarget));
12067 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012068
12069 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12070 // Avoid dereferencing a null pointer here.
12071 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12072
12073 if (!Current.insert(Canonical))
12074 return;
12075
12076 // We know that beyond here, we aren't chaining into a cycle.
12077 if (!Target || !Target->isDelegatingConstructor() ||
12078 Target->isInvalidDecl() || Valid.count(TCanonical)) {
12079 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12080 Valid.insert(*CI);
12081 Current.clear();
12082 // We've hit a cycle.
12083 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12084 Current.count(TCanonical)) {
12085 // If we haven't diagnosed this cycle yet, do so now.
12086 if (!Invalid.count(TCanonical)) {
12087 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012088 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012089 << Ctor;
12090
Richard Smith802c4b72012-08-23 06:16:52 +000012091 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012092 if (TCanonical != Canonical)
12093 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12094
12095 CXXConstructorDecl *C = Target;
12096 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012097 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012098 (void)C->getTargetConstructor()->hasBody(FNTarget);
12099 assert(FNTarget && "Ctor cycle through bodiless function");
12100
Richard Smith802c4b72012-08-23 06:16:52 +000012101 C = const_cast<CXXConstructorDecl*>(
12102 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012103 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12104 }
12105 }
12106
12107 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12108 Invalid.insert(*CI);
12109 Current.clear();
12110 } else {
12111 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12112 }
12113}
12114
12115
Alexis Hunt6118d662011-05-04 05:57:24 +000012116void Sema::CheckDelegatingCtorCycles() {
12117 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12118
Alexis Hunt27a761d2011-05-04 23:29:54 +000012119 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12120 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000012121
Douglas Gregorbae31202011-07-27 21:57:17 +000012122 for (DelegatingCtorDeclsType::iterator
12123 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012124 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012125 I != E; ++I)
12126 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012127
12128 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12129 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012130}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012131
Douglas Gregor3024f072012-04-16 07:05:22 +000012132namespace {
12133 /// \brief AST visitor that finds references to the 'this' expression.
12134 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12135 Sema &S;
12136
12137 public:
12138 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12139
12140 bool VisitCXXThisExpr(CXXThisExpr *E) {
12141 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12142 << E->isImplicit();
12143 return false;
12144 }
12145 };
12146}
12147
12148bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12149 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12150 if (!TSInfo)
12151 return false;
12152
12153 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012154 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012155 if (!ProtoTL)
12156 return false;
12157
12158 // C++11 [expr.prim.general]p3:
12159 // [The expression this] shall not appear before the optional
12160 // cv-qualifier-seq and it shall not appear within the declaration of a
12161 // static member function (although its type and value category are defined
12162 // within a static member function as they are within a non-static member
12163 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012164 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012165 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012166 FindCXXThisExpr Finder(*this);
12167
12168 // If the return type came after the cv-qualifier-seq, check it now.
12169 if (Proto->hasTrailingReturn() &&
David Blaikie6adc78e2013-02-18 22:06:02 +000012170 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012171 return true;
12172
12173 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012174 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12175 return true;
12176
12177 return checkThisInStaticMemberFunctionAttributes(Method);
12178}
12179
12180bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12181 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12182 if (!TSInfo)
12183 return false;
12184
12185 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012186 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012187 if (!ProtoTL)
12188 return false;
12189
David Blaikie6adc78e2013-02-18 22:06:02 +000012190 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012191 FindCXXThisExpr Finder(*this);
12192
Douglas Gregor3024f072012-04-16 07:05:22 +000012193 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012194 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012195 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012196 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012197 case EST_DynamicNone:
12198 case EST_MSAny:
12199 case EST_None:
12200 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012201
Douglas Gregor3024f072012-04-16 07:05:22 +000012202 case EST_ComputedNoexcept:
12203 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12204 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012205
Douglas Gregor3024f072012-04-16 07:05:22 +000012206 case EST_Dynamic:
12207 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor433e0532012-04-16 18:27:27 +000012208 EEnd = Proto->exception_end();
Douglas Gregor3024f072012-04-16 07:05:22 +000012209 E != EEnd; ++E) {
12210 if (!Finder.TraverseType(*E))
12211 return true;
12212 }
12213 break;
12214 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012215
12216 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012217}
12218
12219bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12220 FindCXXThisExpr Finder(*this);
12221
12222 // Check attributes.
12223 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12224 A != AEnd; ++A) {
12225 // FIXME: This should be emitted by tblgen.
12226 Expr *Arg = 0;
12227 ArrayRef<Expr *> Args;
12228 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12229 Arg = G->getArg();
12230 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12231 Arg = G->getArg();
12232 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12233 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12234 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12235 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12236 else if (ExclusiveLockFunctionAttr *ELF
12237 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12238 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12239 else if (SharedLockFunctionAttr *SLF
12240 = dyn_cast<SharedLockFunctionAttr>(*A))
12241 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12242 else if (ExclusiveTrylockFunctionAttr *ETLF
12243 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12244 Arg = ETLF->getSuccessValue();
12245 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12246 } else if (SharedTrylockFunctionAttr *STLF
12247 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12248 Arg = STLF->getSuccessValue();
12249 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12250 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12251 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12252 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12253 Arg = LR->getArg();
12254 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12255 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12256 else if (ExclusiveLocksRequiredAttr *ELR
12257 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12258 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12259 else if (SharedLocksRequiredAttr *SLR
12260 = dyn_cast<SharedLocksRequiredAttr>(*A))
12261 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12262
12263 if (Arg && !Finder.TraverseStmt(Arg))
12264 return true;
12265
12266 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12267 if (!Finder.TraverseStmt(Args[I]))
12268 return true;
12269 }
12270 }
12271
12272 return false;
12273}
12274
Douglas Gregor433e0532012-04-16 18:27:27 +000012275void
12276Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12277 ArrayRef<ParsedType> DynamicExceptions,
12278 ArrayRef<SourceRange> DynamicExceptionRanges,
12279 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012280 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012281 FunctionProtoType::ExtProtoInfo &EPI) {
12282 Exceptions.clear();
12283 EPI.ExceptionSpecType = EST;
12284 if (EST == EST_Dynamic) {
12285 Exceptions.reserve(DynamicExceptions.size());
12286 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12287 // FIXME: Preserve type source info.
12288 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12289
12290 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12291 collectUnexpandedParameterPacks(ET, Unexpanded);
12292 if (!Unexpanded.empty()) {
12293 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12294 UPPC_ExceptionType,
12295 Unexpanded);
12296 continue;
12297 }
12298
12299 // Check that the type is valid for an exception spec, and
12300 // drop it if not.
12301 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12302 Exceptions.push_back(ET);
12303 }
12304 EPI.NumExceptions = Exceptions.size();
12305 EPI.Exceptions = Exceptions.data();
12306 return;
12307 }
12308
12309 if (EST == EST_ComputedNoexcept) {
12310 // If an error occurred, there's no expression here.
12311 if (NoexceptExpr) {
12312 assert((NoexceptExpr->isTypeDependent() ||
12313 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12314 Context.BoolTy) &&
12315 "Parser should have made sure that the expression is boolean");
12316 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12317 EPI.ExceptionSpecType = EST_BasicNoexcept;
12318 return;
12319 }
12320
12321 if (!NoexceptExpr->isValueDependent())
12322 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012323 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012324 /*AllowFold*/ false).take();
12325 EPI.NoexceptExpr = NoexceptExpr;
12326 }
12327 return;
12328 }
12329}
12330
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012331/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12332Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12333 // Implicitly declared functions (e.g. copy constructors) are
12334 // __host__ __device__
12335 if (D->isImplicit())
12336 return CFT_HostDevice;
12337
12338 if (D->hasAttr<CUDAGlobalAttr>())
12339 return CFT_Global;
12340
12341 if (D->hasAttr<CUDADeviceAttr>()) {
12342 if (D->hasAttr<CUDAHostAttr>())
12343 return CFT_HostDevice;
12344 else
12345 return CFT_Device;
12346 }
12347
12348 return CFT_Host;
12349}
12350
12351bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12352 CUDAFunctionTarget CalleeTarget) {
12353 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12354 // Callable from the device only."
12355 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12356 return true;
12357
12358 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12359 // Callable from the host only."
12360 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12361 // Callable from the host only."
12362 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12363 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12364 return true;
12365
12366 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12367 return true;
12368
12369 return false;
12370}
John McCall5e77d762013-04-16 07:28:30 +000012371
12372/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12373///
12374MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12375 SourceLocation DeclStart,
12376 Declarator &D, Expr *BitWidth,
12377 InClassInitStyle InitStyle,
12378 AccessSpecifier AS,
12379 AttributeList *MSPropertyAttr) {
12380 IdentifierInfo *II = D.getIdentifier();
12381 if (!II) {
12382 Diag(DeclStart, diag::err_anonymous_property);
12383 return NULL;
12384 }
12385 SourceLocation Loc = D.getIdentifierLoc();
12386
12387 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12388 QualType T = TInfo->getType();
12389 if (getLangOpts().CPlusPlus) {
12390 CheckExtraCXXDefaultArguments(D);
12391
12392 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12393 UPPC_DataMemberType)) {
12394 D.setInvalidType();
12395 T = Context.IntTy;
12396 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12397 }
12398 }
12399
12400 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12401
12402 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12403 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12404 diag::err_invalid_thread)
12405 << DeclSpec::getSpecifierName(TSCS);
12406
12407 // Check to see if this name was declared as a member previously
12408 NamedDecl *PrevDecl = 0;
12409 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12410 LookupName(Previous, S);
12411 switch (Previous.getResultKind()) {
12412 case LookupResult::Found:
12413 case LookupResult::FoundUnresolvedValue:
12414 PrevDecl = Previous.getAsSingle<NamedDecl>();
12415 break;
12416
12417 case LookupResult::FoundOverloaded:
12418 PrevDecl = Previous.getRepresentativeDecl();
12419 break;
12420
12421 case LookupResult::NotFound:
12422 case LookupResult::NotFoundInCurrentInstantiation:
12423 case LookupResult::Ambiguous:
12424 break;
12425 }
12426
12427 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12428 // Maybe we will complain about the shadowed template parameter.
12429 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12430 // Just pretend that we didn't see the previous declaration.
12431 PrevDecl = 0;
12432 }
12433
12434 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12435 PrevDecl = 0;
12436
12437 SourceLocation TSSL = D.getLocStart();
12438 MSPropertyDecl *NewPD;
12439 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12440 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12441 II, T, TInfo, TSSL,
12442 Data.GetterId, Data.SetterId);
12443 ProcessDeclAttributes(TUScope, NewPD, D);
12444 NewPD->setAccess(AS);
12445
12446 if (NewPD->isInvalidDecl())
12447 Record->setInvalidDecl();
12448
12449 if (D.getDeclSpec().isModulePrivateSpecified())
12450 NewPD->setModulePrivate();
12451
12452 if (NewPD->isInvalidDecl() && PrevDecl) {
12453 // Don't introduce NewFD into scope; there's already something
12454 // with the same name in the same scope.
12455 } else if (II) {
12456 PushOnScopeChains(NewPD, S);
12457 } else
12458 Record->addDecl(NewPD);
12459
12460 return NewPD;
12461}